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
