val sharedFlow = MutableSharedFlow<Int>() // Collector 1 sharedFlow.onEach { println("Collector 1 received: $it") }.launchIn(scope) // Collector 2 sharedFlow.onEach { println("Collector 2 received: $it") }.launchIn(scope) sharedFlow.emit(5)
A SharedFlow emits events to all collectors that are actively collecting. So when you emit 5, both collectors receive it.
val sharedFlow = MutableSharedFlow<Int>() sharedFlow.emit(10) // Collector starts after emit sharedFlow.onEach { println("Received: $it") }.launchIn(scope)
By default, MutableSharedFlow does not replay past events to new collectors. So if the event was emitted before collecting started, the collector misses it.
The replay parameter sets how many past events are replayed to new collectors. The correct parameter name is replay.
emit suspend forever?val sharedFlow = MutableSharedFlow<Int>(replay = 0, extraBufferCapacity = 0) // No collectors started sharedFlow.emit(1) // Suspends here
When replay and extraBufferCapacity are zero, emit suspends until a collector is ready to receive the event.
Setting replay = 1 keeps the last event for new collectors. Setting extraBufferCapacity = 1 allows buffering one event when no collector is active, preventing suspension or loss.
