jdemeulenaere
07/08/2020, 1:56 PMpackage com.example.script
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() {
val count = MutableStateFlow(0)
runBlocking {
// Collect the values in a new coroutine.
val job = launch {
// Prints "3 4 5".
count.take(3).collect {
println("$it ")
}
}
// TODO: Somehow synchronize and suspend here until the coroutine starts collecting
// so that we print "0 1 2" instead.
repeat(3) {
count.value++
}
repeat(3) {
delay(500)
count.value++
}
}
}
jdemeulenaere
07/08/2020, 1:59 PMstreetsofboston
07/08/2020, 2:03 PMvalue
is non-suspending, it races through it.
It works in the second loop, since you do a delay()
there.
Does it work if you add a yield()
call just after count.value++
in the first loop?marstran
07/08/2020, 2:19 PMFlow
is for? A normal (non-buffered) Flow
suspends on emit
until a collector consumes it.Adam Powell
07/08/2020, 2:22 PMCoroutineStart.UNDISPATCHED
will generally do the trick if you're not afraid of experimental APIAdam Powell
07/08/2020, 2:23 PMAdam Powell
07/08/2020, 2:23 PMjulian
07/08/2020, 10:57 PMMutableStateFlow
isn't the best fit. You're having to work too hard to get around its built-in conflation.elizarov
07/08/2020, 11:13 PMChannel
.