In Swift, what happens when two tasks iterate the same AsyncStream or AsyncThrowingStream of chat messages, and how do you give both every message?
answer
- one buffer, one consumer
- Sendable is not multicast
- the throwing stream traps
- one stream per subscriber
basics
~10 sNeither gets every message: streams are single-consumer, and concurrent iteration is documented as a programmer error. In Swift 6.4 AsyncStream splits elements between waiting tasks and AsyncThrowingStream traps. Give each subscriber its own stream.
solid answer
~40 sSwift's streams are **single-consumer**. The documentation calls iterating one stream from two tasks at once a programmer error, and the two types fail differently in Swift 6.4: with `AsyncStream`, each element goes to whichever task is waiting, so the two lists split the messages; with `AsyncThrowingStream`, the second concurrent `next()` traps with *attempt to await next() on more than one task*. The compiler does not stop you, because the stream itself is `Sendable` when its element is; only its `Iterator` is not. To fan out, the producer keeps one continuation per subscriber: `subscribe()` returns a fresh stream, `publish` yields into every stored continuation, and each stream's `onTermination` removes its entry. Since Swift 6.2 the continuation is `Hashable`, so a `Set` can hold them.
code
swift · 23 lines@MainActor final class MessageHub {
private var subscribers: [Int: AsyncStream<String>.Continuation] = [:]
private var nextID = 0
func subscribe() -> AsyncStream<String> {
let (stream, continuation) = AsyncStream.makeStream(of: String.self)
let id = nextID
nextID += 1
subscribers[id] = continuation
continuation.onTermination = { [weak self] _ in
Task { @MainActor in self?.subscribers[id] = nil }
}
return stream
}
func publish(_ message: String) {
for continuation in subscribers.values { continuation.yield(message) }
}
func close() {
for continuation in subscribers.values { continuation.finish() }
}
}go deeper
Recall that an AsyncStream has one consumer: two loops over it do not each get every message.
Explain the split with AsyncStream, the trap with AsyncThrowingStream, and why Sendable on the stream does not mean multicast.
Build the per-subscriber broadcaster, remove subscribers in onTermination with a hop back to the hub's actor, and keep each subscriber's buffer policy deliberate.
Decide where fan-out lives: one hub per data source, owning subscription lifetime and replay rules, rather than streams passed around and shared ad hoc.
## Single consumer by design An `AsyncStream` has **one buffer** and hands each element out **once**. The proposal that introduced it (SE-0314) says that creating multiple iterators "may produce an unexpected series of values" and that "concurrent iteration is considered a programmer error". The iterator's doc comment goes further and says a contending `next()` call "results in a call to `fatalError()`". What the Swift 6.4 runtime actually does differs by type, and a local test shows both: | Stream type | Two tasks iterating at once | Observed in Swift 6.4 | |---|---|---| | `AsyncStream` | each element goes to one waiting task | task A got 1, 3, 5, 7, 9 and task B got 2, 4, 6, 8, 10 | | `AsyncThrowingStream` | the second concurrent `next()` traps | *Fatal error: attempt to await next() on more than one task* | Neither is a broadcast. Code that "works" with `AsyncStream` is silently losing half the messages on each screen, and code built on `AsyncThrowingStream` crashes the first time two readers overlap. ## Why the compiler lets you share it The standard library declares `AsyncStream: @unchecked Sendable where Element: Sendable`, and the same for `AsyncThrowingStream`. Passing a stream of `String` into two tasks is therefore legal in Swift 6 language mode. `Sendable` means the value may cross isolation boundaries safely; it does not mean every holder sees every element. The non-`Sendable` part is the **`Iterator`**, which each `for await` creates inside its own task, so no diagnostic fires. ## Reading one stream twice in a row Sequential loops are not a fix either: - If the first loop ran until the stream finished, a second loop gets `nil` at once; the stream is in its terminal state. - If the first loop left early with `break` while the stream was still referenced, a second loop continues from whatever is buffered next, not from the start. A stream is a queue that is drained, not a collection that is replayed. ## Broadcasting: one stream per subscriber The producer, not the stream, does the fan-out: 1. `subscribe()` creates a fresh stream with `makeStream(of:)`, stores its continuation under a key, and returns the stream. 2. `publish(_:)` yields the message into every stored continuation. 3. Each continuation's `onTermination` removes its own entry, so a screen that stops listening (its task cancelled, its stream released) stops costing anything. 4. `close()` calls `finish()` on every continuation, ending every subscriber's loop. The example keeps the hub on the main actor, and the `@Sendable` termination handler hops back with `Task { @MainActor in ... }` before touching the dictionary (the lesson on actors covers that hop). It captures an integer ID rather than the continuation, so the handler stored inside the stream does not retain the stream's own storage. ## Swift 6.2: continuations are `Hashable` SE-0468 (Swift 6.2) made `AsyncStream.Continuation` and `AsyncThrowingStream.Continuation` `Hashable`; two continuations are equal when they feed the same stream. A broadcaster can keep a `Set` of continuations and remove one by value. The conformance needs the Swift 6.2 runtime, so an app deploying to older systems keeps an explicit ID as in the example. ## Why not one stream and many loops It is tempting to keep one stream and let every screen loop over it, because the stream is already there and already `Sendable`. The cost is hidden until production: with `AsyncStream`, two screens each show roughly half the conversation, and the bug looks like flaky networking; with `AsyncThrowingStream`, the app crashes as soon as the second screen starts reading while the first is waiting. Neither failure shows up in a test with a single reader. A review rule that every `for await` gets a stream nobody else reads, obtained from a `subscribe()`-style method, removes the whole class of bug. ## Things to watch - Each subscriber has its **own buffer and policy**: one slow screen grows only its own buffer. - A subscriber that subscribes late sees only messages published after it subscribed; replaying history is the hub's job. - Remove subscribers on termination; otherwise `publish` keeps yielding into ended streams, each yield returning `.terminated`.
- How does the hub learn that a screen has stopped listening?Through each stream's `onTermination`. When the screen's reading task is cancelled, or its stream is released, the handler runs with `.cancelled` and removes that subscriber. Because the handler is `@Sendable` and may run on any thread, it hops to the hub's actor before touching the dictionary.
- What did Swift 6.2 change that simplifies this hub?SE-0468 made the stream continuations `Hashable`, equal when they feed the same stream, so the hub can store them in a `Set` and remove one by value instead of minting IDs. The conformance needs the Swift 6.2 runtime, so older deployment targets keep the ID-keyed dictionary.
- Because AsyncStream is Sendable, every task that iterates it receives every element.
- A second for await loop over a finished stream replays its elements from the start.
- AsyncStream and AsyncThrowingStream fail the same way when two tasks read them.
- The compiler rejects sharing one AsyncStream<String> between two tasks in Swift 6 mode.
Assumes Swift 6.4; the split and trap behaviours were observed with the Swift 6.4 toolchain, and AsyncStream.Continuation became Hashable in Swift 6.2 (SE-0468).