skip to content

A Swift chat screen breaks out of its for await loop, yet the socket behind the AsyncStream stays open; when does onTermination actually run?

level: seniorimportance: should knowfreq 35%

answer

  1. break drops the iterator, not the stream
  2. finished versus cancelled
  3. the last reference going away
  4. called once, then cleared

basics

~20 s

onTermination runs once: with .finished when the producer calls finish, and with .cancelled when the reading task is cancelled or the stream and its iterators are released. break only drops the iterator, so a stream stored elsewhere stays open.

solid answer

~40 s

`onTermination` fires at most once, for one of three events. The producer calls `finish()` or `finish(throwing:)`, giving `.finished` (`.finished(error)` on `AsyncThrowingStream`). The task iterating the stream is cancelled while it reads, giving `.cancelled`. Or the stream value and every iterator over it are released, which also reports `.cancelled`. A `break` is none of those: it only discards the iterator. If the view model keeps the stream in a stored property, the stream is still alive, `yield(_:)` still enqueues, and the socket stays open. The fix is to tie the stream's end to the screen: run the loop in a task that is cancelled when the screen goes away, or call `finish()` in teardown, or create the stream per reader so it is released with the loop.

code

swift · 25 lines
swift
final class ChatScreen {
    let messages: AsyncStream<String>               // stored: lives as long as the screen
    let input: AsyncStream<String>.Continuation

    init() {
        (messages, input) = AsyncStream.makeStream(of: String.self)
        input.onTermination = { reason in print("onTermination:", reason) }
    }
}

@main struct TerminationDemo {
    static func main() async {
        var screen: ChatScreen? = ChatScreen()
        screen?.input.yield("hello")
        if let messages = screen?.messages {
            for await message in messages {
                print("got", message)
                break                                 // leaves the loop, not the stream
            }
        }
        print(screen!.input.yield("still open?"))
        screen = nil                                  // last reference to the stream goes
        print("screen released")
    }
}

go deeper

for a junior

Recall the two Termination cases, finished and cancelled, and that onTermination is where the producer cleans up.

for a middle

Explain the three triggers and why a break, which only drops the iterator, does not end a stream stored elsewhere.

for a senior

Diagnose the open-socket bug from the stream's lifetime, fix it by cancelling the reading task or finishing in teardown, and keep the @Sendable handler short and lock-free.

for a principal

Set a team convention that every stream-backed producer owns its cleanup in onTermination and that screens end streams explicitly, and review for long-lived stored streams.

## What `onTermination` is `AsyncStream.Continuation.onTermination` is an optional `@Sendable (Termination) -> Void` closure the **producer** installs to clean up: stop a socket, remove a delegate, cancel a timer. `Termination` has two cases on `AsyncStream`, **`.finished`** and **`.cancelled`**; `AsyncThrowingStream` carries the error in **`.finished(Failure?)`**. The implementation swaps the handler out before calling it, so it runs **at most once**, and the closure and everything it captured are released afterwards. ## The three triggers | Trigger | Value received | What the reader sees | |---|---|---| | Producer calls `finish()` / `finish(throwing:)` | `.finished` / `.finished(error)` | buffered elements, then `nil` or the error | | The reading task is cancelled while iterating | `.cancelled` | `next()` returns `nil`, possibly after elements already buffered | | The stream and all its iterators are released | `.cancelled` | nothing: no reader is left | The third row comes from the stream's internal storage: when the last copy of the stream and of its iterators goes away, the stream cancels itself. A local test with the Swift 6.4 toolchain shows it: a stream nobody ever iterated reports `.cancelled` as soon as it goes out of scope. ## Why `break` is not on the list A `for await` loop owns an **iterator**, not the stream. `break` ends the loop and releases that iterator, but if the stream is a stored property of a view model or screen, the stream keeps its state alive. The example shows the result: - after `break`, `yield("still open?")` returns `.enqueued`, so the producer keeps running; - `onTermination` fires with `.cancelled` only when the screen object, and with it the stream, is released. With a stream held in a local `let`, the same `break` ends the stream when that scope ends, which is why this bug appears only once the stream moves into a long-lived object. ## Tying the stream's end to the screen - **Cancel the reading task.** Start the loop in a `Task` you keep and cancel when the screen disappears. Cancellation while waiting in `next()` triggers `.cancelled` and closes the socket. (Task handles and cancellation have their own lesson.) - **Finish from teardown.** If the producer object outlives the screen, call `continuation.finish()` when the screen goes away. - **Make one stream per reader.** A `subscribe()` method that returns a fresh stream lets the stream die with the loop that reads it. - **Do not rely on `break`** to release resources unless nothing else holds the stream. ## Writing the handler safely 1. **It may run on any thread.** The closure is `@Sendable` and may run inside task cancellation; the source points to the same deadlock considerations as `withTaskCancellationHandler(operation:onCancel:)`. Keep it short, take no lock the cancelling code might hold, and hop to an actor if the socket requires it. 2. **Install it before starting the source**, so an early cancellation still cleans up. 3. **Treat its captures as owned until termination.** The stream holds the closure, so a socket captured there lives until the stream ends. 4. **After termination**, further `yield(_:)` calls return `.terminated`; check that result if lost messages matter. ## A checklist for the review When a pull request adds a stream-backed producer, a reviewer can ask four questions: 1. Which object owns the stream, and how long does that object live? 2. What ends the stream when the screen goes away: a cancelled task, an explicit `finish()`, or the stream's release? 3. Does `onTermination` stop the source, and is it set before the source starts? 4. Does the handler do only quick, thread-safe work, with any actor-isolated cleanup sent back to its actor? If the first answer is "a long-lived service" and the second is "the loop's `break`", the socket will stay open. ## Traps - Expecting `.finished` after `break`; the loop ending is not the stream finishing. - Capturing `self` strongly in the handler of a stream stored on `self`: the stream holds the handler and the handler holds `self`, a cycle that only termination breaks. - Assuming cancellation discards buffered elements; the reader may still receive ones already buffered before `nil`.

  • What does the screen's loop see when its task is cancelled while it waits in next()?
    The stream terminates: `onTermination` runs first with `.cancelled`, then `next()` returns `nil` and the loop ends normally, with no error thrown from an `AsyncStream`. Elements already buffered may still be delivered before that `nil`, and later `yield(_:)` calls return `.terminated`.
  • Does onTermination run when the producer calls finish()?
    Yes, with `.finished` on `AsyncStream`, or `.finished(error)` on `AsyncThrowingStream`, where the error is `nil` for a normal finish. It runs at most once, so a later cancellation does not call it again; the handler was cleared when it ran.
  • How can the onTermination closure keep the socket alive longer than expected?
    The stream stores the closure, and the closure captures the socket strongly. Until the stream terminates, the socket stays alive with it. If the stream lives in a long-lived object and never finishes, so does the socket; once termination runs, the handler is cleared and the capture released.

  • Breaking out of a for await loop always calls onTermination with .finished.
  • onTermination runs once per iterator that stops reading the stream.
  • onTermination fires only on cancellation, never after the producer calls finish().
  • Releasing a stream that nobody iterated never calls onTermination.
  • Cancelling the reading task throws CancellationError out of an AsyncStream loop.