Est.

Event-Driven Architecture in Native iOS Apps With Combine and AsyncStream

Combine keeps its operators, AsyncStream needs explicit completion, and actors tie them together.

· 9 min read
Cover illustration for “Event-Driven Architecture in Native iOS Apps With Combine and AsyncStream”
Swift Architecture · November 26, 2026 · 9 min read · 1,932 words

Event-driven architecture in native iOS apps can use both Combine and AsyncStream. Combine supplies declarative pipelines, while AsyncStream connects event sources to concurrency-native consumers. Their coexistence works when actor isolation protects shared state and every stream has a defined path to completion and cleanup.

Why Combine and AsyncStream are both still in production codebases in 2026

In 2026, iOS apps have two ways to process events. In Combine, a Publisher emits values over time, operators transform them, and Subscribers receive the results. Scheduling and subscription lifetime belong to that pipeline, with AnyCancellable supporting cancellation management. SwiftUI also accepts publishers directly through .onReceive.

AsyncStream presents events as values consumed by a for await loop. Its construction closure receives a continuation through which the producer yields values, while the consumer runs within a Task. The stream remains open until it is finished or consumption terminates through cancellation. This is a different lifetime contract. A codebase containing both models therefore has to reconcile not only value types, but also who owns subscriptions, tasks, and termination at each boundary.

The one production-critical difference developers miss when moving from Combine to AsyncStream

The dangerous assumption is that producing the last value also completes the stream. Combine publishers for finite work usually signal completion when the work ends, but open-ended publishers still need their lifetime managed. When an AsyncStream construction closure returns, the stream stays open. If it yields integers 1–5 without calling continuation.finish(), the consumer waits for another value. A statement after the loop, such as print("This line will NEVER execute"), remains unreachable.

A timer-based heartbeat makes the consequence more concrete. The broken version starts a timer but neither invalidates it nor finishes the stream when the heartbeat count reaches its limit. The result combines a suspended consumer with a resource leak. The working version retains the timer reference, invalidates it at the count limit, and calls continuation.finish(). Its onTermination handler also invalidates the timer when consumption ends through cancellation.

The absence of a crash makes this easy to miss. Tasks never finish, async functions never return, and timers or observers keep running as memory use grows. AsyncStream supports open-ended sources such as sockets and sensors, so the construction closure cannot determine when those sources are done. LLM token streams have the same requirement. The last token is a value, and stream completion still requires an explicit signal.

What Combine does that AsyncStream cannot replace cleanly

Combine is still the better fit when the pipeline itself defines much of what the code does. Operators including debounce, removeDuplicates, map, and combineLatest make transformation and coordination declarative. A debounced text-field validation pipeline can express those rules without manually reconstructing them around an asynchronous loop. This model also works well for updates from Timer.publish and for system notification streams. The operator set is the distinction.

When sources change on their own, combineLatest and zip keep coordinating publisher output, while async let and task groups organize concurrent work without the same ongoing reactive composition. Replacing such a pipeline with AsyncStream moves responsibility for expressing its coordination rules into application logic.

Combine also provides a demand model through which subscribers indicate how many values they can handle. AsyncStream has no equivalent subscriber-demand protocol. When the consumer falls behind, a producer that sends values at a high rate can fill an unchecked buffer. Where demand and declarative coordination define the feature, retaining Combine preserves capabilities that a plain asynchronous sequence does not replace.

What AsyncStream does that Combine handles awkwardly

AsyncStream fits sources whose lifetime is tied to the task that consumes them, especially hardware sensors, sockets, and actor-isolated services. The consumer processes events in a for await loop rather than maintaining a separate subscription model. Cancellation connects consumption to the task’s lifetime. An onTermination handler then provides the place to release the underlying resource, whereas Combine requires cancellables management for its subscriptions.

Actor boundaries give this arrangement another purpose. Swift 6 concurrency checking checks the safety of values crossing isolation boundaries, including Sendable requirements between a background sensor actor and a @MainActor ViewModel. The boundary becomes visible to the compiler. It is no longer merely an agreement that producers and consumers will use the correct thread.

A single AsyncStream<ViewSignal> can also serve as a ViewModel’s unidirectional input channel. With one consuming event loop, signals have one ordered processing path and one concurrency boundary. With this setup, behavior can be deterministic and tests can replay signals.

How to layer Combine and AsyncStream inside an MVVM-C codebase

The practical assignment follows those different strengths. In a layered application codebase, Service and Repository layers host declarative Combine pipelines, actor-isolated boundaries expose AsyncStream events, and an @Observable ViewModel exposes state to the View. A compact wiring diagram reads as Service/Repository → AsyncStream across the actor boundary → ViewModel → observable state → View. Combine lives inside the service pipeline where its operators are needed. The diagram separates event transport from state observation.

Within the Repository, search, debounced validation, and combineLatest across data sources remain publisher operations. Supabase Realtime channels can send typed INSERT/UPDATE/DELETE events through a publisher in this layer before a bridge passes them up to the next layer. The ViewModel need not inherit that subscription design. It receives the events through the boundary selected for its concurrency model.

At that boundary, a sensor actor, WebSocket manager actor, or Realtime bridge actor owns the event source and serializes access to shared continuation state. The ViewModel consumes the resulting stream in a Task containing a for await loop on its own isolation domain. Its observable state then drives the UI. A View using @State or @Bindable with an @Observable ViewModel can refresh without importing Combine into the View file.

A Combine sink can forward publisher values into an AsyncStream continuation through yield, while a custom Publisher can expose an AsyncStream to a Combine consumer. These are opposite conversions. Each belongs at the boundary where the next layer needs a different consumption model.

The race condition hiding inside a naive multi-consumer AsyncStream

Broadcasting events introduces shared mutable state that a single consuming loop does not solve. The naive design puts a dictionary of continuations in a plain class and allows concurrent callers of load() to register consumers or emit values through it. Two callers can access that collection concurrently. The dictionary becomes a data race, and Swift 6 strict concurrency checking can reject the unsafe access.

To make this safe, the dictionary of continuations goes inside an actor. Each consumer receives its own stream, whose continuation is registered with that actor, and events are yielded to the registered continuations. The actor serializes collection reads and writes. When a consumer terminates, onTermination arranges removal of its continuation through the actor. Broadcast semantics come from this registry.

An AsyncPassthrough<Value> helper can extract that pattern into a reusable primitive with the broadcast role of PassthroughSubject and a Swift Concurrency lifecycle. The actor protects the shared collection on which delivery and cleanup both depend. Although actor calls introduce suspension points, those hops are cooperative rather than a requirement for a preemptive thread switch at every call. Removing isolation to avoid await removes the correctness guarantee.

Applying finish discipline and onTermination to real event sources

Every source needs a finish strategy and a cleanup handler. For finite sources, including a paginated API response or an animation sequence, the completion point is immediately after the final yield. Calling continuation.finish() lets the consumer leave its loop. Returning from the producer’s setup closure does not. When moving from Combine, each stream needs to be checked for code that assumes it will finish on its own.

The implementation retains the timer reference, calls timer.invalidate() at the count limit, and finishes the continuation. It also registers onTermination to invalidate the timer if the consuming task is cancelled first. Reaching the count limit cannot be the only opportunity to release the timer.

Sensors and sockets instead have open-ended lifetimes. Their finish strategy follows the source’s end or the end of the consumer’s interest. For hardware feeds, onTermination tears down the sensor subscription when the Task that consumes it in the ViewModel is cancelled. Streams backed by sockets also need cleanup when they terminate. A producer’s ability to keep emitting is not a reason to keep resources active after consumption ends.

LLM streams are open while generation proceeds but have an explicit generation-complete signal. Each token becomes a yield, and that completion signal triggers continuation.finish() so the UI’s loop does not remain suspended after the response ends. Apple’s Foundation Models framework, available in iOS 26, does not remove this requirement when model output is wrapped in AsyncStream. Phantomstory Demo, an indie iOS app founder with hands-on experience integrating LLMs into agentic iOS features, treats the explicit finish call as essential. The termination contract remains the same across these sources.

Where this architecture fits into a broader iOS performance and team-scaling strategy

Correct stream lifetime is only part of responsive event processing. Event buses and stream infrastructure must also keep the main thread free to run. Parsing, image decoding, and heavy computation belong on background actors, with a @MainActor ViewModel receiving processed state through the actor-sourced stream. That separation protects UI work as events arrive. It supports smooth frame rates on ProMotion displays without making the ViewModel responsible for raw-data processing.

The same boundaries also define responsibilities across a team. Adopting strict concurrency in new modules first, then migrating existing modules opportunistically, extends compiler-enforced safety without requiring a single wholesale rewrite. In Swift 6 language mode, concurrency violations are errors. A solo developer gains a safety net. A larger team gains a shared contract for how modules exchange data and protect mutable state.

These concerns stand out in connected-device and vehicle companion apps because telemetry keeps arriving. Actor-isolated AsyncStream ingestion fits that flow, while Supabase Realtime’s CDC-based approach suits lower-frequency state synchronization between a device and a backend. Those are different workloads with different latency requirements. For sub-50ms telemetry with many connections, CDC latency needs to be checked against what the use case needs. Even with clean application-layer wiring, the backend transport still needs to meet that requirement.

A decision map for choosing between Combine, AsyncStream, and async/await on the next feature

Diagram: Combine vs AsyncStream vs async/await: A Decision Map. Visualizes: Visualize the branching decision logic developers should use when choosing between Combine, AsyncStream, and plain async/await.

The first branch is whether the operation produces one result or repeated events. If it is a single API call, a sequential fetch chain, or a fire-and-forget write, plain async/await is the direct fit. No stream abstraction is needed for that decision. If values arrive repeatedly, the next branch is whether their processing depends on declarative operators or continuous coordination across sources.

If the feature needs debounce, removeDuplicates, or combineLatest, choose Combine. The same choice fits framework-provided publishers for text input, notifications, and timers, or an existing Combine implementation whose migration cost exceeds the feature’s benefit. If the source instead lives behind an actor boundary, AsyncStream fits sensors, WebSockets, Realtime bridges, and token generators. It also fits a ViewModel requiring one ordered signal channel. In those cases, tying cancellation to the task releases source resources when consumption ends.

Swift 6.2’s Observations AsyncSequence tracks the observable properties accessed inside its initialization closure and streams their state changes. For teams targeting iOS 26+ and Swift 6.2+, it can reduce the need for Combine in basic observation plumbing. Combine may still supply the required operators. State observation and event transformation need not use the same tool.

When those branches meet, conversion belongs at their boundary. A Combine publisher can feed an asynchronous consumer through publisher.values, allowing the consuming Task to own cancellation without hybrid subscription management. An explicit sink-to-continuation bridge serves publisher-to-stream forwarding, while a custom Publisher supports the reverse direction.

More in Swift Architecture