AsyncSequence, AsyncStream and continuations

suggest change

An async function returns one value (see async and await). Many things produce several values over time: lines read from a file, progress updates of a download, sensor readings, messages from a socket. Swift 5.5 added AsyncSequence for them. It's like Sequence, but getting the next element can suspend, so you loop over it with for await.

This article covers:

Type Use it for
AsyncSequence protocol for anything you can for await over
AsyncStream<Element> a ready-made async sequence you feed by calling yield
AsyncThrowingStream<Element, Error> the same, but it can end with an error
withCheckedContinuation turning one callback into one await
withCheckedThrowingContinuation the same, for callbacks that can fail

The examples were compiled with Swift 6.4 on Windows, in the Swift 6 language mode:

swiftc -swift-version 6 -parse-as-library main.swift

AsyncSequence, AsyncStream and continuations need Swift 5.5. makeStream(of:) needs Swift 5.9. Typed errors in async sequences (some AsyncSequence<Element, Failure>, throws(APIError) in next()) need Swift 6.0. Task.sleep(for:), used to simulate slow work, needs Swift 5.7.

for await and writing an AsyncSequence

An AsyncSequence has a makeAsyncIterator() method. The iterator has a mutating func next() async -> Element?. It returns nil when the sequence ends. That's the whole protocol, the async version of Sequence and IteratorProtocol (see Iterator).

Here is a countdown that waits 50 ms before producing each number:

struct Countdown: AsyncSequence {
    let start: Int

    struct AsyncIterator: AsyncIteratorProtocol {
        var current: Int

        mutating func next() async -> Int? {
            guard current > 0 else { return nil }
            try? await Task.sleep(for: .milliseconds(50))
            defer { current -= 1 }
            return current
        }
    }

    func makeAsyncIterator() -> AsyncIterator {
        AsyncIterator(current: start)
    }
}

@main
struct Main {
    static func main() async {
        for await n in Countdown(start: 3) {
            print(n)
        }
        print("liftoff")

        // what for-await does under the hood
        var it = Countdown(start: 2).makeAsyncIterator()
        while let n = await it.next() {
            print("manual:", n)
        }

        let evens = Countdown(start: 10)
            .filter { $0.isMultiple(of: 2) }
            .map { "#\($0)" }
            .prefix(3)
        for await s in evens { print(s, terminator: " ") }
        print()

        print(await Countdown(start: 5).contains(3))
        print(await Countdown(start: 5).first { @Sendable n in n < 3 } ?? -1)
        print(await Countdown(start: 4).reduce(0, +))
        print(type(of: evens))
    }
}

Output:

3
2
1
liftoff
manual: 2
manual: 1
#10 #8 #6 
true
2
10
AsyncPrefixSequence<AsyncMapSequence<AsyncFilterSequence<Countdown>, String>>

Things to notice:

The @Sendable in first { @Sendable n in n < 3 } is needed in Swift 6 mode when you call it from main-actor code, such as main(). Without it the compiler says sending value of non-Sendable type '(Int) async -> Bool' risks causing data races. The same applies to allSatisfy, contains(where:) and reduce(into:) with a closure. reduce(0, +) and the lazy map / filter compile without it.

Throwing sequences and typed failures

If next() can throw, consumers write for try await. Since Swift 6.0 the protocol has a Failure associated type, and the iterator can use typed throws. The type also has primary associated types, so a function can return some AsyncSequence<Element, Failure> and hide a long type like the one above:

enum APIError: Error { case serverDown(page: Int) }

// Pages of results from a paginated API; fails on `failAt`.
struct Pages: AsyncSequence {
    typealias Element = [String]
    let failAt: Int?

    struct AsyncIterator: AsyncIteratorProtocol {
        let failAt: Int?
        var page = 1

        mutating func next() async throws(APIError) -> [String]? {
            if page == failAt { throw .serverDown(page: page) }
            guard page <= 3 else { return nil }
            defer { page += 1 }
            return ["item\(page)a", "item\(page)b"]
        }
    }

    func makeAsyncIterator() -> AsyncIterator {
        AsyncIterator(failAt: failAt)
    }
}

// Hide the concrete type behind primary associated types (Swift 6.0)
func pageSummaries(failAt: Int? = nil) -> some AsyncSequence<String, APIError> {
    Pages(failAt: failAt).map { $0.joined(separator: ",") }
}

@main
struct Main {
    static func main() async {
        do {
            for try await summary in pageSummaries() {
                print(summary)
            }
            for try await page in Pages(failAt: 2) {
                print("got", page)
            }
        } catch {
            print("failed:", error)
        }
    }
}

Output:

item1a,item1b
item2a,item2b
item3a,item3b
got ["item1a", "item1b"]
failed: serverDown(page: 2)

When next() throws, the loop ends and the error goes to the catch. In older Swift versions, write mutating func next() async throws -> [String]? and return some AsyncSequence without the type arguments.

Writing an iterator by hand works when the values are computed on demand, like pages or a countdown. When values are pushed to you by someone else (callbacks, delegates, timers), use AsyncStream instead.

AsyncStream

AsyncStream is a concrete AsyncSequence you build with a closure. The closure gets a continuation (AsyncStream<Element>.Continuation). You call yield(_:) on it to send a value and finish() to end the stream. The stream buffers values until the consumer takes them.

func numbers(upTo n: Int) -> AsyncStream<Int> {
    AsyncStream { continuation in
        Task {
            for i in 1...n {
                try? await Task.sleep(for: .milliseconds(20))
                continuation.yield(i)
            }
            continuation.finish()
        }
    }
}

actor JobQueue {
    private var jobs: [String]
    init(_ jobs: [String]) { self.jobs = jobs }
    func pop() -> String? { jobs.isEmpty ? nil : jobs.removeFirst() }
}

@main
struct Main {
    static func main() async {
        for await n in numbers(upTo: 3) {
            print("received", n)
        }

        // the closure runs once, synchronously, inside the initializer
        let words = AsyncStream<String> { continuation in
            print("build closure runs")
            continuation.yield("alpha")
            continuation.yield("beta")
            continuation.finish()
            continuation.yield("ignored after finish")
        }
        print("stream created")
        for await w in words { print(w) }

        // pull-based: the closure is called each time the consumer asks
        let queue = JobQueue(["resize", "upload", "notify"])
        let jobs = AsyncStream { await queue.pop() }   // nil ends the stream
        for await job in jobs { print("job:", job) }
    }
}

Output:

received 1
received 2
received 3
build closure runs
stream created
alpha
beta
job: resize
job: upload
job: notify

How it works:

If you forget to call finish(), the consumer's for await loop never ends. Every stream that has an end should call finish() on every path.

makeStream: getting the continuation out

Often the code that produces values isn't inside the build closure. Since Swift 5.9, AsyncStream.makeStream(of:) returns the stream and its continuation as a tuple:

let (stream, continuation) = AsyncStream.makeStream(of: Int.self)

Before 5.9 people did the same by assigning the continuation to an outer variable from inside the closure. makeStream is shorter and doesn't need an implicitly unwrapped optional.

AsyncThrowingStream: bridging a callback API

AsyncThrowingStream is the version that can fail. It has finish(throwing:), and consumers use for try await. It's the natural fit for callback APIs that report progress several times and then succeed or fail once.

Compare this with wrapping a callback in Completion handler with input argument: there the callback delivers one result. Here the callback fires many times:

import Foundation

// A callback-based API we can't change: reports progress several times,
// then completes once with a result.
final class LegacyDownloader: Sendable {
    func download(
        _ name: String,
        progress: @escaping @Sendable (Double) -> Void,
        completion: @escaping @Sendable (Result<Int, Error>) -> Void
    ) {
        DispatchQueue.global().async {
            for step in 1...4 {
                Thread.sleep(forTimeInterval: 0.02)
                if name.hasSuffix(".bad") && step == 3 {
                    completion(.failure(DownloadError.corrupted(name)))
                    return
                }
                progress(Double(step) / 4)
            }
            completion(.success(name.count * 1000))
        }
    }
}

enum DownloadError: Error { case corrupted(String) }

enum DownloadEvent: Sendable {
    case progress(Double)
    case finished(bytes: Int)
}

extension LegacyDownloader {
    func events(for name: String) -> AsyncThrowingStream<DownloadEvent, Error> {
        let (stream, continuation) = AsyncThrowingStream.makeStream(of: DownloadEvent.self)
        download(name) { fraction in
            continuation.yield(.progress(fraction))
        } completion: { result in
            switch result {
            case .success(let bytes):
                continuation.yield(.finished(bytes: bytes))
                continuation.finish()
            case .failure(let error):
                continuation.finish(throwing: error)
            }
        }
        return stream
    }
}

@main
struct Main {
    static func main() async {
        let downloader = LegacyDownloader()
        for name in ["photo.jpg", "movie.bad"] {
            do {
                for try await event in downloader.events(for: name) {
                    switch event {
                    case .progress(let p): print("\(name): \(Int(p * 100))%")
                    case .finished(let bytes): print("\(name): done, \(bytes) bytes")
                    }
                }
            } catch {
                print("\(name): failed with \(error)")
            }
        }
    }
}

Output:

photo.jpg: 25%
photo.jpg: 50%
photo.jpg: 75%
photo.jpg: 100%
photo.jpg: done, 9000 bytes
movie.bad: 25%
movie.bad: 50%
movie.bad: failed with corrupted("movie.bad")

The pattern is always the same: each "value" callback calls yield, the "done" callback calls finish(), and the "error" callback calls finish(throwing:). An enum like DownloadEvent lets one stream carry different kinds of events.

There is also continuation.yield(with: result), which yields a success value or finishes with the error of a Result.

Buffering policies

What happens when the producer is faster than the consumer? By default (.unbounded) the stream keeps every value in memory until it's consumed. For a fast producer and a slow consumer this grows without limit. You can choose a bounded buffer when you create the stream:

yield returns a YieldResult that tells you what happened to the value:

func describe(_ r: AsyncStream<Int>.Continuation.YieldResult) -> String {
    switch r {
    case .enqueued(let remaining): "enqueued (room for \(remaining) more)"
    case .dropped(let value): "dropped \(value)"
    case .terminated: "terminated"
    @unknown default: "unknown"
    }
}

func fill(_ policy: AsyncStream<Int>.Continuation.BufferingPolicy, label: String) async {
    let (stream, continuation) = AsyncStream.makeStream(of: Int.self, bufferingPolicy: policy)
    print(label)
    // produce 5 values before anyone reads
    for i in 1...5 {
        print("  yield \(i): \(describe(continuation.yield(i)))")
    }
    continuation.finish()
    print("  yield 6: \(describe(continuation.yield(6)))")
    var received: [Int] = []
    for await n in stream { received.append(n) }
    print("  consumer got \(received)")
}

@main
struct Main {
    static func main() async {
        await fill(.unbounded, label: ".unbounded")
        await fill(.bufferingOldest(2), label: ".bufferingOldest(2)")
        await fill(.bufferingNewest(2), label: ".bufferingNewest(2)")
    }
}

Output:

.unbounded
  yield 1: enqueued (room for 9223372036854775807 more)
  yield 2: enqueued (room for 9223372036854775807 more)
  yield 3: enqueued (room for 9223372036854775807 more)
  yield 4: enqueued (room for 9223372036854775807 more)
  yield 5: enqueued (room for 9223372036854775807 more)
  yield 6: terminated
  consumer got [1, 2, 3, 4, 5]
.bufferingOldest(2)
  yield 1: enqueued (room for 1 more)
  yield 2: enqueued (room for 0 more)
  yield 3: dropped 3
  yield 4: dropped 4
  yield 5: dropped 5
  yield 6: terminated
  consumer got [1, 2]
.bufferingNewest(2)
  yield 1: enqueued (room for 1 more)
  yield 2: enqueued (room for 0 more)
  yield 3: dropped 1
  yield 4: dropped 2
  yield 5: dropped 3
  yield 6: terminated
  consumer got [4, 5]

Note that yield never waits. AsyncStream has no back-pressure: it can't slow the producer down, it can only buffer or drop. When a consumer is already waiting in next(), the value goes straight to it and isn't buffered at all. .terminated means the stream is finished or nobody is listening any more, so the producer can stop.

onTermination: stopping the producer

A producer should stop when the consumer goes away. Set continuation.onTermination to a closure. It's called exactly once, with .finished when the stream ended normally (finish() was called), or .cancelled when the consumer stopped listening: the task running the loop was cancelled, or the stream was released.

func ticks(every interval: Duration, label: String, limit: Int = .max) -> AsyncStream<Int> {
    AsyncStream { continuation in
        let producer = Task {
            var n = 0
            while !Task.isCancelled && n < limit {
                try? await Task.sleep(for: interval)
                n += 1
                continuation.yield(n)
            }
            continuation.finish()
        }
        continuation.onTermination = { reason in
            print("[\(label)] terminated: \(reason)")
            producer.cancel()      // stop producing when nobody listens
        }
    }
}

@main
struct Main {
    static func main() async {
        // 1. the producer finishes on its own
        for await n in ticks(every: .milliseconds(10), label: "finite", limit: 2) {
            print("finite:", n)
        }

        // 2. the consumer breaks out of the loop
        for await n in ticks(every: .milliseconds(10), label: "break") {
            print("break:", n)
            if n == 3 { break }
        }

        // 3. the consuming task is cancelled
        let consumer = Task {
            for await n in ticks(every: .milliseconds(30), label: "cancel") {
                print("cancel:", n)
            }
            print("loop ended, isCancelled = \(Task.isCancelled)")
        }
        try? await Task.sleep(for: .milliseconds(100))
        consumer.cancel()
        await consumer.value
    }
}

Output (the number of cancel: lines may differ between runs):

finite: 1
finite: 2
[finite] terminated: finished
break: 1
break: 2
break: 3
[break] terminated: cancelled
cancel: 1
cancel: 2
cancel: 3
[cancel] terminated: cancelled
loop ended, isCancelled = true

Things to know:

Bridging a delegate API to a stream

Delegate callbacks are another common source of values (see also Observer for the NotificationCenter flavour). The adapter object becomes the delegate and forwards each callback to a continuation. Here the sensor is a stand-in for something like CLLocationManager:

import Foundation

// A delegate-based API, in the style of many Apple frameworks.
protocol SensorDelegate: AnyObject {
    func sensor(_ sensor: Sensor, didMeasure celsius: Double)
    func sensorDidStop(_ sensor: Sensor)
}

final class Sensor: @unchecked Sendable {
    weak var delegate: SensorDelegate?
    private var timer: DispatchSourceTimer?
    private var samples = [21.5, 21.7, 22.0, 22.4]

    func start() {
        let timer = DispatchSource.makeTimerSource(queue: .global())
        timer.schedule(deadline: .now() + 0.02, repeating: 0.02)
        timer.setEventHandler { [self] in
            if samples.isEmpty {
                stop()
                delegate?.sensorDidStop(self)
            } else {
                delegate?.sensor(self, didMeasure: samples.removeFirst())
            }
        }
        self.timer = timer
        timer.resume()
    }

    func stop() {
        timer?.cancel()
        timer = nil
        print("sensor stopped")
    }
}

// Adapter: acts as the delegate and forwards every callback into a stream.
final class SensorAdapter: SensorDelegate, Sendable {
    private let continuation: AsyncStream<Double>.Continuation
    init(_ continuation: AsyncStream<Double>.Continuation) {
        self.continuation = continuation
    }

    func sensor(_ sensor: Sensor, didMeasure celsius: Double) {
        continuation.yield(celsius)
    }

    func sensorDidStop(_ sensor: Sensor) {
        continuation.finish()
    }
}

extension Sensor {
    func measurements() -> AsyncStream<Double> {
        AsyncStream { continuation in
            let adapter = SensorAdapter(continuation)
            delegate = adapter                  // weak reference
            continuation.onTermination = { reason in
                _ = adapter                     // the closure keeps the adapter alive
                if case .cancelled = reason { self.stop() }
            }
            start()
        }
    }
}

@main
struct Main {
    static func main() async {
        for await t in Sensor().measurements() {
            print("reading: \(t) C")
        }
        print("stream finished")

        for await t in Sensor().measurements() where t > 21.6 {
            print("first warm reading: \(t) C")
            break
        }
        print("after the loop")
    }
}

Output:

reading: 21.5 C
reading: 21.7 C
reading: 22.0 C
reading: 22.4 C
sensor stopped
stream finished
first warm reading: 21.7 C
sensor stopped
after the loop

Two details matter here:

for await ... where filters elements, just like a normal for loop.

Continuations for a single result

withCheckedContinuation and withCheckedThrowingContinuation turn a callback that fires once into an await. You saw the basic form in async and await. The function suspends the current task, gives you a CheckedContinuation, and the task resumes when you call one of:

The rule: resume exactly once, on every path. "Checked" means the runtime verifies this. Resuming twice is a fatal error:

func twice(completion: @escaping @Sendable (Int) -> Void) {
    completion(1)
    completion(2)     // bug: calls back twice
}

@main
struct Main {
    static func main() async {
        let v = await withCheckedContinuation { continuation in
            twice { continuation.resume(returning: $0) }
        }
        print(v)
    }
}

Output (the program crashes):

_Concurrency/CheckedContinuation.swift:169: Fatal error: SWIFT TASK CONTINUATION MISUSE: main() tried to resume its continuation more than once, returning 2!

Never resuming is worse, because nothing crashes. The task stays suspended forever. When the last reference to an unresumed continuation goes away, the checked version prints a warning to stderr:

import Foundation

func lookUp(_ key: String, completion: @escaping @Sendable (Int?) -> Void) {
    DispatchQueue.global().async {
        if key.isEmpty { return }        // bug: forgets to call completion
        completion(key.count)
    }
}

func lookUp(_ key: String) async -> Int? {
    await withCheckedContinuation { continuation in
        lookUp(key) { continuation.resume(returning: $0) }
    }
}

@main
struct Main {
    static func main() async {
        print("lookUp(\"swift\") =", await lookUp("swift") ?? -1)
        let task = Task { await lookUp("") }
        try? await Task.sleep(for: .milliseconds(300))
        task.cancel()   // doesn't help: nothing will ever resume it
        print("gave up waiting")
    }
}

Output:

lookUp("swift") = 5
SWIFT TASK CONTINUATION MISUSE: lookUp(_:) leaked its continuation without resuming it. This may cause tasks waiting on it to remain suspended forever.
gave up waiting

task.cancel() doesn't help. Cancellation only sets a flag, and a suspended continuation doesn't look at it. If the underlying API can be cancelled, combine the continuation with withTaskCancellationHandler, as shown in Tasks and cancellation.

withUnsafeContinuation and withUnsafeThrowingContinuation have the same API without these checks. They are slightly faster, and misuse is undefined behavior. Use the checked versions unless profiling shows they matter.

Storing a continuation until a callback arrives

Sometimes the callback comes from somewhere else, for example a delegate method that is called when a connection is ready. Then you store the continuation and resume it later. Two rules keep this safe: protect the stored continuation with a lock or an actor, and take it out of storage before resuming, so it can't be resumed twice:

import Foundation
import Synchronization

enum ConnectionError: Error { case alreadyWaiting, refused }

// Callbacks arrive later, from somewhere else (a delegate, a socket, a UI event).
// We park the continuation until then.
final class Connection: Sendable {
    private let pending = Mutex<CheckedContinuation<String, Error>?>(nil)

    func connect(to host: String) async throws -> String {
        try await withCheckedThrowingContinuation { continuation in
            let ok = pending.withLock { slot in
                guard slot == nil else { return false }
                slot = continuation
                return true
            }
            guard ok else {
                continuation.resume(throwing: ConnectionError.alreadyWaiting)
                return
            }
            startHandshake(host)
        }
    }

    // Called by the networking layer when the handshake ends.
    private func handshakeDidFinish(_ result: Result<String, Error>) {
        // take the continuation out first, so it can't be resumed twice
        let continuation = pending.withLock { slot in
            defer { slot = nil }
            return slot
        }
        continuation?.resume(with: result)
    }

    private func startHandshake(_ host: String) {
        DispatchQueue.global().asyncAfter(deadline: .now() + 0.05) {
            self.handshakeDidFinish(host.hasPrefix("bad")
                ? .failure(ConnectionError.refused)
                : .success("session-\(host.count)"))
        }
    }
}

@main
struct Main {
    static func main() async {
        let conn = Connection()
        do {
            print(try await conn.connect(to: "example.com"))
            print(try await conn.connect(to: "bad.host"))
        } catch {
            print("error:", error)
        }

        // a second waiter while the first is pending is rejected
        let first = Task { try await conn.connect(to: "one.org") }
        try? await Task.sleep(for: .milliseconds(10))
        do {
            _ = try await conn.connect(to: "two.org")
        } catch {
            print("second waiter:", error)
        }
        print("first waiter:", (try? await first.value) ?? "nil")
    }
}

Output:

session-11
error: refused
second waiter: alreadyWaiting
first waiter: session-7

Only one continuation fits in the slot, so a second concurrent connect is rejected instead of overwriting (and leaking) the first one. Mutex comes from the Synchronization module (Swift 6.0). An actor works too, but an actor method is async, and the body of withCheckedThrowingContinuation is a synchronous closure.

Use a continuation when the callback fires once. When it can fire many times, a continuation is the wrong tool (resuming twice crashes). Use an AsyncStream instead.

One stream, one consumer

An AsyncStream isn't a broadcast. If two tasks iterate the same stream, each element goes to only one of them:

@main
struct Main {
    static func main() async {
        let (stream, continuation) = AsyncStream.makeStream(of: Int.self)
        let a = Task { for await n in stream { print("A got", n) } }
        let b = Task { for await n in stream { print("B got", n) } }
        try? await Task.sleep(for: .milliseconds(50))
        for i in 1...4 { continuation.yield(i) }
        continuation.finish()
        await a.value
        await b.value
    }
}

Output (which task gets which number varies from run to run):

B got 1
A got 2
B got 3
A got 4

To deliver every value to several listeners, give each listener its own stream and keep a list of continuations:

actor Broadcaster<Element: Sendable> {
    private var subscribers: [Int: AsyncStream<Element>.Continuation] = [:]
    private var nextID = 0

    func subscribe() -> AsyncStream<Element> {
        let (stream, continuation) = AsyncStream.makeStream(of: Element.self)
        let id = nextID
        nextID += 1
        subscribers[id] = continuation
        continuation.onTermination = { _ in
            Task { await self.unsubscribe(id) }
        }
        return stream
    }

    func send(_ value: Element) {
        for continuation in subscribers.values { continuation.yield(value) }
    }

    func finish() {
        for continuation in subscribers.values { continuation.finish() }
    }

    var count: Int { subscribers.count }

    private func unsubscribe(_ id: Int) { subscribers[id] = nil }
}

func collectAll(_ stream: AsyncStream<Double>) async -> [Double] {
    var got: [Double] = []
    for await p in stream { got.append(p) }
    return got
}

func waitForSpike(_ stream: AsyncStream<Double>) async -> String {
    for await p in stream where p > 101 {
        return "B saw \(p) and left"
    }
    return "B: no spike"
}

@main
struct Main {
    static func main() async {
        let prices = Broadcaster<Double>()
        let a = Task { [s = await prices.subscribe()] in await collectAll(s) }
        let b = Task { [s = await prices.subscribe()] in await waitForSpike(s) }
        print("subscribers:", await prices.count)

        for p in [100.0, 100.5, 101.25, 99.0] {
            await prices.send(p)
            try? await Task.sleep(for: .milliseconds(10))
        }
        print(await b.value)
        print("subscribers:", await prices.count)
        await prices.finish()
        print("A got", await a.value)
    }
}

Output:

subscribers: 2
B saw 101.25 and left
subscribers: 1
A got [100.0, 100.5, 101.25, 99.0]

When B returns from its loop, its stream is released, onTermination runs, and the broadcaster drops that continuation. onTermination is synchronous and the actor's methods are async, so it starts a small Task to get back onto the actor. The [s = await prices.subscribe()] capture list subscribes before the task starts, so no early value is missed, and doesn't leave a reference to the stream in main().

Async sequences in the SDKs

Foundation on Apple platforms provides many ready-made async sequences: URL.lines, FileHandle.bytes, URLSession.bytes(from:) and NotificationCenter.notifications(named:). Task groups are async sequences too (see Structured concurrency with async let and TaskGroup). The open source swift-foundation used on Windows and Linux doesn't have URL.lines, so this snippet wasn't run:

import Foundation

// Apple platforms only
let url = URL(string: "https://www.swift.org/")!
for try await line in url.lines.prefix(5) {
    print(line)
}

For operators the standard library lacks, such as debounce, throttle, merge, zip and combineLatest, use the swift-async-algorithms package.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents