StateFlow: Hot State Holder for UI
Use StateFlow as a reactive state container and observe it in ViewModels.
What Is StateFlow?
StateFlow is a hot, state-holding Flow that always has a value and emits updates to all collectors. It replaces LiveData in modern Kotlin architectures.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val stateFlow = MutableStateFlow(0) // initial value
println("Current: ${stateFlow.value}")
stateFlow.value = 42
println("Updated: ${stateFlow.value}")
}MutableStateFlow vs StateFlow
MutableStateFlow is the mutable implementation used internally. Expose StateFlow (read-only) to external observers by casting or using .asStateFlow().
import kotlinx.coroutines.flow.*
class CounterViewModel {
private val _count = MutableStateFlow(0) // mutable internally
val count: StateFlow<Int> = _count.asStateFlow() // read-only externally
fun increment() { _count.value++ }
fun decrement() { _count.value-- }
}