liveBook · Manning

State flow

As explained in Kotlin in Action, 2E

A StateFlow is a Kotlin coroutines hot-flow implementation for communicating and observing state, retaining a current state value for collectors.

A StateFlow is a hot Kotlin coroutine flow for communicating changing state. It keeps a current value, remains active without collectors, and lets multiple subscribers observe updates. section 16.3 section 16.3.2

Listing 16.13 A basic implementation of a view counter that uses a state flow
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.*
 
class ViewCounter {
    private val _counter = MutableStateFlow(0)    #1
    val counter = _counter.asStateFlow()
 
    fun increment() {
        _counter.update { it + 1 }
    }
}
 
fun main() {
    val vc = ViewCounter()
    vc.increment()
    println(vc.counter.value)
    // 1
}

Use the compact view-counter implementation as a starting pattern: keep MutableStateFlow private, expose StateFlow with asStateFlow, initialize its value, and update it through update. section 16.3.2

The basic StateFlow pattern provides:

  • A required initial value that represents the state immediately. section 16.3.2
  • A value property for safely reading the current state without suspension. section 16.3.2
  • The update function for safe concurrent writes; direct read-modify-write operations such as _counter.value++ are not atomic. section 16.3.2
  • Equality-based conflation, so assigning the existing value does not emit another element. section 16.3.3
  • A way to convert a cold flow into a hot state flow with stateIn. section 16.3.2

Choosing StateFlow over SharedFlow

Use StateFlow when subscribers need the current state or accumulated history. For example, storing messages in a MutableStateFlow<List<String>> lets a subscriber joining later read [Hello!, Hi!, Hola!]. A SharedFlow instead broadcasts only emissions available while a subscriber is present. section 16.3.3 section 16.3.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains creation, exposure, atomic updates, conflation, cold-flow conversion, and comparison with SharedFlow.
Examples
Demonstrates view counters, concurrent increments, direction selection, temperature state, and accumulated message history.
What it assumes
Assumes familiarity with Kotlin coroutines, flows, collectors, and concurrent systems.
What you can do after
Apply StateFlow by exposing read-only state, updating it atomically, collecting changes, and converting cold flows with stateIn.
How it connects
Links StateFlow with hot flows, SharedFlow, cold flows, stateIn, collectors, subscribers, and equality-based conflation.

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.