scana
12/01/2021, 3:23 PMMutableStateFlow would only emit last item in this example (running from Kotlin scratch file)?
val x = MutableStateFlow("Test")
CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch {
x.collect {
println(it)
}
}
x.value = "First"
x.value = "Second"
x.value = "Fourth"
println("Waiting...")
Thread.sleep(1000)
Result:
Waiting...
FourthJoffrey
12/01/2021, 3:31 PMStateFlow should mean that collectors should only care about the "current state" (or latest state). So the fact that you see all updates or just the last should be considered an implementation detail.Joffrey
12/01/2021, 3:33 PMlaunch started collecting before you reach the sleep. What likely happens here is that the root coroutine blazes through the whole code and reaches Thread.sleep before the launched coroutine even started, so when the launch collects the flow, the flow is already in its last state.scana
12/01/2021, 3:34 PMursus
12/01/2021, 11:51 PM