juliocbcotta
05/07/2022, 10:18 AMimport kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.runBlocking
suspend fun flowsWithCombine() {
val numbersFlow = flowOf(1, 2, 3)
val lettersFlow = flowOf("A")
combine(numbersFlow, lettersFlow) { number, letter ->
"$number$letter"
}.collect {
// delay(100)
println(it)
}
}
fun main() = runBlocking {
val deferred: Deferred<Unit> = async {
println("waiting...")
flowsWithCombine()
}
println(deferred.await())
}
If I run the code as above, I get
waiting...
1A
2A
3A
kotlin.Unit
if I uncomment the delay
the result changes
waiting...
1A
3A
kotlin.Unit
Why is that ?Nick Allen
05/07/2022, 6:00 PMcombine
acts on "the most recently emitted values". With the delay, the coroutines reading the input finish, before the coroutine emitting values has a change to emit the "2A". Without the delay, the "1A" and "2A" showing up seems more like an implementation detail that I would not rely on.juliocbcotta
05/07/2022, 6:06 PMNick Allen
05/07/2022, 6:14 PMconflate
.