StateFlow
- Kotlin course
- Advanced
- Lesson 7/83
- 5 min
Learn state streams with StateFlow.
What is StateFlow?
StateFlow is a hot flow that always has a value. As the value changes it delivers the latest state to collectors; a late collector still gets the current value immediately.
It is created with MutableStateFlow(initial); you read and write through .value. Writing the same value again does not emit (conflation). StateFlow is a common tool for UI state: it fits the data held in a ViewModel.
Using StateFlow
You create state with MutableStateFlow and update it through .value. A collector gets the current value and following changes via .collect.
Example: val state = MutableStateFlow(0); state.value = 1. When you open state.collect { v -> println(v) } inside a launch, you print both the current value and later changes. Writing the same value again does not emit; only distinct values reach collectors.
Practice Write and read state with StateFlow
Define val state = MutableStateFlow(0). Print the initial value with println("Initial: ${state.value}"). Then set state.value = 5 and print println("Now: ${state.value}").
Starter code
// Use StateFlow
// write here
fun main() {
}Sample solution
fun main() {
val state = MutableStateFlow(0)
println("Initial: ${state.value}")
state.value = 5
println("Now: ${state.value}")
}Expected output
Initial: 0 Now: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement about StateFlow is correct?
- It emits only once
- Its value must be null
- It always has a value Correct answer
- It needs no coroutine
Explanation: StateFlow always carries an initial value.
2 Complete the StateFlow initial value
val state = MutableStateFlow(____)
val state = MutableStateFlow(0)
Explanation: StateFlow needs an initial value.
3 Match StateFlow parts
| Term | Meaning |
|---|---|
MutableStateFlow |
State holder |
.value |
Read and write |
.collect |
Collecting |
conflation |
Skips same value |