How do you turn a chat socket's delegate callbacks into a Swift AsyncThrowingStream that a screen reads with for try await?
answer
- a continuation that may escape
- one yield per callback
- finish or finish(throwing:) once
- onTermination closes the socket
- makeStream returns both halves
basics
~20 sCreate an AsyncThrowingStream, keep its Continuation where the delegate methods can reach it, call yield(_:) per message and finish(throwing:) when the socket closes, and close the socket in onTermination. makeStream(of:) returns stream and continuation together.
solid answer
~40 sI make an object that is the socket's delegate and owns an `AsyncThrowingStream<String, any Error>` plus its `Continuation`, which I get from `AsyncThrowingStream.makeStream(of:)` (Swift 5.9) instead of smuggling it out of the initializer's closure. Each `didReceive` callback calls `continuation.yield(message)`; the close callback calls `continuation.finish(throwing: error)`, where `nil` ends the loop normally and an error makes `for try await` throw it. I set `continuation.onTermination` to close the socket, so cancelling the reading task, or releasing the feed and its stream, also shuts the connection. The continuation is `Sendable` and its calls are serialized, so callbacks on any thread are fine, and unlike a checked continuation it may yield any number of times before finishing once.
code
swift · 40 lines@MainActor protocol ChatSocketDelegate: AnyObject {
func socket(_ socket: ChatSocket, didReceive message: String)
func socketDidClose(_ socket: ChatSocket, error: (any Error)?)
}
@MainActor final class ChatSocket { // the legacy, delegate-based SDK
weak var delegate: (any ChatSocketDelegate)?
func open() {}
func close() {}
}
@MainActor final class MessageFeed: ChatSocketDelegate {
let messages: AsyncThrowingStream<String, any Error>
private let continuation: AsyncThrowingStream<String, any Error>.Continuation
private let socket = ChatSocket()
init() {
(messages, continuation) = AsyncThrowingStream.makeStream(of: String.self)
let socket = self.socket
continuation.onTermination = { _ in
Task { @MainActor in socket.close() } // finished, reader cancelled or stream released
}
socket.delegate = self
socket.open()
}
func socket(_ socket: ChatSocket, didReceive message: String) {
continuation.yield(message)
}
func socketDidClose(_ socket: ChatSocket, error: (any Error)?) {
continuation.finish(throwing: error) // nil finishes normally
}
}
@MainActor func showChat(_ feed: MessageFeed) async throws {
for try await message in feed.messages {
print(message)
}
}go deeper
Recall the three producer calls: yield for each message, finish when the socket closes, finish(throwing:) when it fails.
Walk through the bridge: makeStream(of:), storing the continuation, mapping each delegate method, and closing the socket in onTermination.
Point out the traps: no backpressure from yield, out-of-order delivery from concurrent callbacks, the @Sendable handler in Swift 6 mode, and the any Error constraint.
Argue for exposing only the stream as the module's async surface and keeping the delegate type internal, so callers never depend on the legacy SDK.
## Why a stream and not a checked continuation A delegate-based socket SDK reports events by calling methods on an object you register: one call per incoming message, one call when the connection closes. A checked continuation (the lesson on suspension points and continuations covers it) models **one** result and must be resumed exactly once, so it fits a single `connect` call but not a feed of messages. **`AsyncStream`** and **`AsyncThrowingStream`** fill that gap (SE-0314, Swift 5.5): the producer side is a **`Continuation`** you may call many times, and the consumer side is an `AsyncSequence` read with `for await`. The stream's continuation is a value you are expected to store, for example in the delegate object, and call later from whatever thread the callbacks use. ## The continuation's calls | Call | Effect on the reader | Typical callback | |---|---|---| | `yield(_:)` | delivers or buffers one element | `didReceive message` | | `finish()` | the loop ends normally once the buffer drains | clean close | | `finish(throwing:)` | the loop throws that error (`AsyncThrowingStream` only) | close with an error | | `onTermination` | your cleanup closure, run once at the end | stop the socket | Some details matter in production: - `yield(_:)` **never waits**. It returns a `YieldResult` at once (`@discardableResult`, so ignoring it compiles). With the default `.unbounded` policy, messages that arrive before anyone iterates are buffered and delivered in order later. - `finish()` is idempotent: "Calling this function more than once has no effect." Elements already buffered are still delivered before the loop sees the end. - After `finish`, further `yield(_:)` calls return `.terminated` and the message is dropped. - `finish(throwing: nil)` finishes normally, so you can pass the delegate's optional error straight through. ## Getting the continuation out: closure or `makeStream` The original initializer, `AsyncThrowingStream { continuation in ... }`, runs its closure synchronously inside `init`. A delegate object therefore used to copy the continuation into a stored property from inside that closure, usually through an implicitly unwrapped optional. **`makeStream(of:throwing:bufferingPolicy:)`** (SE-0388, Swift 5.9, back-deployed) returns the tuple `(stream:, continuation:)` directly, which reads better and lets both be `let` properties. One limit: `AsyncThrowingStream`'s initializers and `makeStream` are constrained to `Failure == any Error`. Writing `AsyncThrowingStream<String, SocketError> { ... }` fails with *initializer 'init(_:bufferingPolicy:_:)' requires the types 'SocketError' and 'any Error' be equivalent*, so a typed socket error has to travel as `any Error`. ## Cleanup with `onTermination` Set `onTermination` before the socket starts. It receives a `Termination` value: `.finished(error)` when you call `finish`, `.cancelled` when the reading task is cancelled or the stream is released. Closing the socket there means nobody has to remember to do it when a screen goes away. The closure is `@Sendable`, so in Swift 6 language mode what it captures must be safe to send; in the example the socket and the delegate are `@MainActor` types, and the handler hops back with `Task { @MainActor in ... }`. ## Threading and ordering The continuation is `Sendable`, and the source documents that "all calls to the continuation are serialized". It also warns that yielding from multiple concurrent contexts "could result in out-of-order delivery", so if a socket SDK calls back on several threads, order is only what the SDK guarantees. The reader side is different: the stream's iterator is not `Sendable`, and one stream is meant to have one reader. If two screens need the same messages, the feed should hand each its own stream rather than share one. When the delegate callbacks already arrive on the main thread, as in the example, marking the feed `@MainActor` keeps its own state safe and makes the Swift 6 checks pass without extra locking. ## Steps in order 1. Create the stream and continuation with `makeStream(of:)` and keep both. 2. Set `onTermination` to stop the source. 3. Register as the delegate, then start the source. 4. Map each callback to `yield(_:)` or `finish(throwing:)`. 5. Expose only the stream to readers; keep the continuation private. ## Mistakes reviewers catch - Keeping a checked continuation in the delegate and resuming it per message; the second resume traps with *SWIFT TASK CONTINUATION MISUSE*. - Forgetting `finish` on close, so the reader's loop waits forever. - Exposing the continuation publicly, so any caller can finish the feed. - Starting the socket before `onTermination` is set, leaving a window with no cleanup.
- Why not wrap the delegate with withCheckedThrowingContinuation instead?A checked continuation must be resumed exactly once, so it models one result such as a connect call. A socket delivers many messages; a second `resume` on a checked continuation traps with *SWIFT TASK CONTINUATION MISUSE*. A stream's continuation can `yield` any number of times and is finished once, which matches a feed.
- What happens to messages that arrive before the screen starts its loop?With the default `.unbounded` policy they are buffered, and the first loop to call `next()` receives them in order. A bounded policy such as `.bufferingNewest(n)` would drop some, and `yield(_:)` reports that in its `YieldResult` as `.dropped`.
- Can the feed expose AsyncThrowingStream<String, SocketError> to get a typed error?Not with the public initializers: `AsyncThrowingStream`'s `init` and `makeStream` require `Failure == any Error`, and the compiler rejects a concrete error type there. Keep `any Error` in the stream and cast in the `catch`; a typed failure needs a hand-written `AsyncSequence` whose iterator declares `throws(SocketError)`.
- An AsyncStream continuation may be used only inside the closure that receives it.
- yield(_:) suspends the delegate callback until the reader takes the message.
- finish() throws away messages that are already buffered.
- onTermination runs only on cancellation, never after finish().
- Resuming a checked continuation once per socket message is a valid bridge.