MutableStateFlow represents changeable state in Kotlin coroutines. Create it with an initial value, keep it private, and expose a read-only StateFlow to subscribers. 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
}
A view counter demonstrates the standard pattern: initialize MutableStateFlow, expose asStateFlow(), update with update, and read the current value without suspending. section 16.3.2
Use MutableStateFlow for state that must remain safe and observable:
- Read the current state through value. section 16.3.2
- Update state with update rather than relying on a nonatomic ++ operation. section 16.3.2
