StateFlow helps your app react to changes in data automatically. It keeps your app's state updated and UI in sync without extra work.
StateFlow for reactive state in Android Kotlin
private val _state = MutableStateFlow(initialValue) val state: StateFlow<Type> = _state // To update state: _state.value = newValue
Use MutableStateFlow to change the state inside your class.
Expose StateFlow to other classes to observe changes without allowing them to modify the state.
private val _count = MutableStateFlow(0) val count: StateFlow<Int> = _count // Update count _count.value = 5
private val _text = MutableStateFlow("") val text: StateFlow<String> = _text // Update text _text.value = "Hello"
This program creates a simple counter using StateFlow. It prints the count every time it changes. When increment() is called, the count updates and the new value prints automatically.
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.runBlocking import kotlinx.coroutines.launch class Counter { private val _count = MutableStateFlow(0) val count: StateFlow<Int> = _count fun increment() { _count.value += 1 } } fun main() = runBlocking { val counter = Counter() val job = launch { counter.count.collect { value -> println("Count is: $value") } } counter.increment() // Count becomes 1 counter.increment() // Count becomes 2 job.cancel() }
StateFlow always has a current value, so you can get it anytime with .value.
Use collect to listen for changes and update UI or other parts of your app.
Remember to cancel collectors when they are no longer needed to avoid memory leaks.
StateFlow holds and emits state updates reactively.
Use MutableStateFlow to change state, and expose StateFlow to observe it.
Collect StateFlow to react to changes and update your UI automatically.