Stop An AsyncStream When Its Consumer Leaves
Turning a callback into an AsyncStream is usually the easy part. Deciding when the callback source should stop is where the interesting bugs show up.
A view disappears, but its monitor stays alive. A loop uses break, but the producer keeps generating values. A slow consumer quietly accumulates an unbounded buffer.
Let’s build a small network-path observation that has an explicit owner. The same lifetime questions apply to progress feeds, sensor callbacks, and delegate adapters.
September 2026 review: the Network/SwiftUI example type-checks with Xcode 27 in Swift 6 mode for an iOS 17 deployment target. Separate stream checks ran on macOS 27; this is not a claim of testing airplane-mode transitions on an iPhone.
Decide whether values are state or events
For a connection banner, we care about the most recent network-path state. If the UI is busy, replaying every intermediate change is not useful.
That makes a one-element newest-value buffer a reasonable choice:
let (stream, continuation) = AsyncStream.makeStream(
of: Bool.self,
bufferingPolicy: .bufferingNewest(1)
)
The AsyncStream design supports explicit buffering policies and reports when yielding drops a value. Yielding does not wait for the consumer to catch up. A bounded buffer limits pending values; it does not slow the producer down.
This policy would be wrong for “charge this customer” or “save this edit.” Those are commands we cannot casually discard. If every item matters, choose a backpressure-aware or durable processing design instead of changing the buffer size until the problem is less visible.
Return the stream and its stop operation
NWPathMonitor has its own lifetime. Our wrapper should expose that lifetime instead of hoping an iterator’s destruction lines up with the feature’s needs.
import Foundation
import Network
struct PathUpdates: Sendable {
let values: AsyncStream<Bool>
private let stop: @Sendable () -> Void
init() {
let monitor = NWPathMonitor()
let (stream, continuation) = AsyncStream.makeStream(
of: Bool.self,
bufferingPolicy: .bufferingNewest(1)
)
values = stream
stop = {
monitor.cancel()
continuation.finish()
}
continuation.onTermination = { @Sendable _ in
monitor.cancel()
}
monitor.pathUpdateHandler = { path in
continuation.yield(path.status == .satisfied)
}
monitor.start(queue: DispatchQueue(label: "blog.path-updates"))
}
func cancel() {
stop()
}
}
There are two cleanup paths on purpose.
The stream’s termination callback cancels the underlying monitor when iteration terminates through the stream machinery, including consumer cancellation. The explicit cancel() method lets our owner stop the source even if it leaves a loop normally or never starts iterating at all.
Calling finish() closes the stream for further yields; any values already buffered can still be consumed before iteration ends. Canceling the monitor stops the source of new path updates. These are related operations with different jobs.
Apple documents the monitor’s lifecycle in NWPathMonitor. Create a fresh wrapper for a fresh observation rather than trying to restart a canceled monitor.
I keep this wrapper scoped to one consumer. Copying the struct copies handles to the same stream and stop operation; it does not create an independent subscription. If several features need path information, let one longer-lived model own the monitor and expose its current state to those features.
Put cleanup next to the loop
Here is the SwiftUI side:
import SwiftUI
struct ConnectionBanner: View {
@State private var pathAvailable: Bool?
var body: some View {
Text(status)
.task {
let updates = PathUpdates()
defer { updates.cancel() }
for await available in updates.values {
guard !Task.isCancelled else { break }
pathAvailable = available
}
}
}
private var status: String {
switch pathAvailable {
case true: "Network path available"
case false: "No network path"
case nil: "Checking network path…"
}
}
}
The defer is easy to audit: whenever this task’s scope exits, its observation is stopped. It covers a future early return or break as well as the current loop.
SwiftUI manages the view task’s cancellation. That still does not excuse an expensive loop body from cooperating with cancellation. If you add a long operation after receiving each value, that operation can delay the scope’s exit and therefore its deferred cleanup.
The optional state also avoids showing “offline” before the first callback arrives. Unknown is a real state; treating it as a failed connection creates an unnecessary flash of error UI.
A satisfied path is not a successful request
The banner deliberately says “network path,” not “server online.” A route can exist while the service is down, authentication has expired, or a request fails for another reason.
Do not make this Boolean the gatekeeper for every URLSession request. Attempt the operation, handle its actual result, and use path information to improve the explanation or retry experience. In an offline-capable app, local edits should remain usable regardless of this banner.
For richer UI, yield your own small sendable snapshot with the specific path properties the feature needs. Keep NWPath inspection inside the adapter rather than making every view interpret networking policy independently.
Check the paths that demos tend to skip
You can test stream mechanics without changing the machine’s network connection. Create a stream/continuation pair and control it directly:
let (stream, continuation) = AsyncStream.makeStream(
of: Int.self,
bufferingPolicy: .bufferingNewest(1)
)
continuation.yield(1)
continuation.yield(2)
for await value in stream {
assert(value == 2)
break
}
// The stream and producer are still retained here.
continuation.finish()
That example makes the normal-exit case visible. A break is a decision by the loop; it is not an explicit command to stop some retained external producer. We should issue that command through our owner.
The executable checks for this post verify newest-value buffering, a retained stream after break, explicit finishing, repeated finishing, rejected yields after termination, and consumer-task cancellation. For the Network integration, add a device check: open the screen, change connectivity, leave the screen, and confirm that the owner releases the observation. Repeat the navigation several times.
The useful habit is small: when you wrap a callback source, write its stop path at the same time as its start path. A clean for await loop should also have a clean answer for who turns the source off.