Predict the output
What does the collector print?
fun main() = runBlocking {
val state = MutableStateFlow(0)
val job = launch { state.collect { println(it) } }
yield()
state.value = 1
state.value = 1
yield()
job.cancel()
}Hint 1 of 2
Does a new collector see the current value?
Hint 2 of 2
What does StateFlow do with an equal value?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 0, then 1
Correct. The initial value is replayed, and setting the same value again is skipped.
Why not the others?
- B 0, then 1, then 1. StateFlow ignores a value equal to the current one.
- C 1, then 1. A new collector gets the current value (0) first.
- D Nothing, because the collector starts too late. StateFlow replays the current value to new collectors.