stateIn converts a cold Kotlin Flow into a hot state flow that runs in a specified coroutine scope and retains the latest emitted value for subscribers. section 16.3.2
Converting a temperature flow
val temps = getTemperatures() runBlocking { val tempState = temps.stateIn(this) println(tempState.value) delay(800.milliseconds) println(tempState.value) } The first read accesses the current state; after the upstream flow emits, the later read returns its latest value. section 16.3.2
The operator has deliberately simple lifecycle behavior:
- It always starts the upstream flow in the supplied coroutine scope rather than accepting a starting strategy. section 16.3.2
- It continues supplying the latest value through the state flow's value property until that scope is cancelled. section 16.3.2
- Multiple collectors or value accesses do not execute the upstream cold flow repeatedly. section 16.3.2
- As a state flow, it participates in equality-based conflation: assigning the same value produces no new emission. section 16.3.2
Use stateIn when consumers need both collection and direct access to the current value, while the upstream flow should run within an existing coroutine scope. section 16.3.2
