Could anyone please help me with understanding why...
# coroutines
s
Could anyone please help me with understanding why
MutableStateFlow
would only emit last item in this example (running from Kotlin scratch file)?
Copy code
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:
Copy code
Waiting...
Fourth
j
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
Thank you so much @Joffrey - great explanation. I actually now see this conflation being mentioned in the documentation 🤦
👍 1
u
its a race, thats why, put sleep between .value = x, youll see more prints