liveBook · Manning

MutableSharedFlow

As explained in Kotlin in Action, 2E

MutableSharedFlow is a kotlinx.coroutines type that represents a shared flow whose emissions and configuration can be changed by its producer.

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.
CH16_F05_Isakova

Shows the broadcast relationship between one shared-flow emission and all currently collecting subscribers. section 16.3.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains construction, encapsulation, emission, subscription timing, replay, and the related shareIn conversion, without deeper implementation internals.
Examples
Uses a RadioStation broadcasting random integers, delayed collectors, replayed messages, and shared sensor temperatures.
What it assumes
Assumes familiarity with Kotlin coroutines, CoroutineScope, launch, Flow, emit, delay, and collect.
What you can do after
Apply it via kotlinx.coroutines to broadcast emissions, expose a read-only flow, and replay recent values for new subscribers.
How it connects
Connects SharedFlow with cold flow, Flow, coroutines, collect, and shareIn.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.