MutableSharedFlow broadcasts emitted values to all subscribers that are currently collecting. Producers emit independently of collectors, unlike cold flows, and can configure replay for new subscribers. section 16.3.1
Broadcasting messages
private val _messageFlow = MutableSharedFlow<Int>() val messageFlow = _messageFlow.asSharedFlow() fun beginBroadcasting(scope: CoroutineScope) { scope.launch { while (true) { delay(500.milliseconds) _messageFlow.emit(Random.nextInt(0..10)) } } } Keep the mutable flow private and expose the read-only SharedFlow view. Multiple collectors of messageFlow receive the same emissions while subscribed. section 16.3.1
Configure delivery behavior according to subscriber timing:
- Without replay, subscribers receive only emissions occurring after collect starts. section 16.3.1
- Set replay = 5 to cache the latest five values for newly subscribed collectors. section 16.3.1
- Use shareIn when an existing cold Flow should be converted into one shared stream for multiple collectors. section 16.3.1
Figure 16.5 Shared flows operate in a broadcast fashion. When an element is emitted into the shared flow, all subscribers currently collecting the flow will receive this emission.
Shows the broadcast relationship between one shared-flow emission and all currently collecting subscribers. section 16.3.1
