The cold/hot distinction determines whether a subscription starts a new upstream execution or joins an existing one. Cold Observables—an HTTP call, a file read, a Kotlin Flow—replay their full producer logic per subscriber. Hot Observables—a WebSocket message feed, a DOM event stream, a Kafka consumer—emit regardless of whether anyone is listening and share the same sequence across all subscribers. Multicasting bridges the two. `publish()` converts a cold Observable into a `ConnectableObservable` that only begins emitting after an explicit `connect()` call, enabling multiple subscribers to synchronize on the same upstream activation. Before `connect()`, subscribers register interest; after it, they receive the same items. `share()` adds reference counting: it auto-connects when the first subscriber arrives and auto-disconnects when the last one leaves, making it the safe default for sharing HTTP responses or WebSocket frames across multiple UI components. `publishReplay(n)` buffers the last n items for late subscribers—useful for state streams where a new subscriber should receive the current value immediately. In RxJS this is `shareReplay(1)`, one of the most commonly used multicasting operators in Angular codebases. Kotlin's `SharedFlow` and `StateFlow` implement the same semantics natively: `StateFlow` always holds and replays the most recent value; `SharedFlow` with a replay cache behaves like `publishReplay`. Reactor's `Flux.share()` and `Flux.publish()` mirror RxJS semantics. Spring Cloud Gateway uses multicasting internally to broadcast upstream responses to multiple concurrent SSE clients without re-executing the upstream request per client. The practical risk of getting this wrong: wrapping a cold Observable in a component that expects hot behavior causes each subscriber to independently trigger the side effect—an extra HTTP call, a duplicate database read, or a redundant file system operation. This is a silent bug that only manifests under multiple-subscription conditions, which often means it reaches production before anyone notices.
Comments on "Hot vs Cold Streams & Multicasting"
Create a free account or sign in to join the discussion.
Sign in to join the conversation