liveBook · Manning

stateIn

As explained in Kotlin in Action, 2E

stateIn is a kotlinx.coroutines Flow operator that converts a flow into a state flow running in a specified coroutine scope.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains conversion, scope lifetime, repeated-access behavior, and equality-based conflation, but defers detailed starting strategies.
Examples
Uses a temperature flow to demonstrate reading the current value before and after an upstream emission.
What it assumes
Assumes familiarity with cold flows, collectors, emitted values, and coroutine scopes.
What you can do after
Apply it via kotlinx.coroutines Flow to create a scoped state flow with direct latest-value access.
How it connects
Connects cold flows, hot flows, state flows, shared flows, shareIn, collectors, and coroutine scopes.

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.