https://kotlinlang.org logo
Title
s

scana

12/01/2021, 3:23 PM
Could anyone please help me with understanding why
MutableStateFlow
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...
Fourth
j

Joffrey

12/01/2021, 3:31 PM
State flows are conflated. Basically the fact that it's a
StateFlow
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.
Now as to what exactly is happening here. You're using multiple threads here, so there is no guarantee the initial
launch
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.
s

scana

12/01/2021, 3:34 PM
Thank you so much @Joffrey - great explanation. I actually now see this conflation being mentioned in the documentation 🤦
👍 1
u

ursus

12/01/2021, 11:51 PM
its a race, thats why, put sleep between .value = x, youll see more prints