liveBook · Manning

Hot flow

As explained in Kotlin in Action, 2E

A hot flow is a stream whose emissions occur independently of whether any collector is currently subscribed and whose emitted items can be shared among multiple collectors.

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

This diagram shows the broadcast rule: one SharedFlow emission reaches every subscriber currently collecting it. section 16.3.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains SharedFlow construction, subscription timing, replay, StateFlow comparison, and cold-to-hot conversion.
Examples
Demonstrates a random-number radio broadcast, delayed subscription, temperature sharing with shareIn, and message-history state.
What it assumes
Builds on coroutines and suspending functions before introducing flows as sequential values over time.
What you can do after
Apply SharedFlow or StateFlow to broadcast concurrent events, represent changing state, and select behavior for late subscribers.
How it connects
Connects hot flows with cold flows, SharedFlow, StateFlow, coroutines, shareIn, stateIn, and flow operators.

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.