ConcurrencyMidMCQ

What is `AsyncStream` and what problem does it solve?

Test your knowledge:

Explanation & Code

Answer: AsyncStream converts callback or delegate-based event sources into an AsyncSequence you can iterate over with for await. It bridges event-driven code into structured concurrency.

Code Example:

// Wrapping a delegate/callback pattern into AsyncStream
func locationUpdates() -> AsyncStream<CLLocation> {
    AsyncStream { continuation in
        let manager = CLLocationManager()
        let delegate = LocationDelegate { location in
            continuation.yield(location)     // emit each update
        }
        manager.delegate = delegate
        manager.startUpdatingLocation()

        continuation.onTermination = { _ in
            manager.stopUpdatingLocation()   // cleanup on cancel
        }
    }
}

// Consuming it cleanly with for await
Task {
    for await location in locationUpdates() {
        print("New location: \(location.coordinate)")
    }
}

Use for: Location updates, WebSocket messages, notifications, sensor data, any ongoing event stream.

Rate your understanding:

Ready to practice more Concurrency?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.