A hot flow emits independently of collectors and shares emissions among multiple subscribers. Use it for events or state changes that occur whether or not a consumer is currently listening. Unlike a cold flow, subscribing does not start its producing logic. section 16.1.2 section 16.3
Kotlin supplies two main hot-flow forms:
- SharedFlow broadcasts values to current subscribers. Late subscribers receive only values emitted after they subscribe, unless replay is configured. section 16.3.1
- StateFlow represents one state value and emits only when that value changes according to equality. section 16.3.3
- shareIn and stateIn convert a cold flow into a shared hot flow. section 16.4
Broadcasting through a SharedFlow
Keep the mutable flow private, expose its read-only SharedFlow view, and launch a coroutine to emit values. Multiple collectors of messageFlow receive each value while subscribed; emitting begins explicitly rather than through collection. class RadioStation { 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)) } } } section 16.3.1
Choose SharedFlow for broadcast-style events whose subscribers may come and go. Consider reframing event history as StateFlow when late consumers must see prior updates; storing the history as state can avoid replay and timing complexity. section 16.3.3
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.
This diagram shows the broadcast rule: one SharedFlow emission reaches every subscriber currently collecting it. section 16.3.1
