Hey, I have been playing with flows and I found an...
# coroutines
j
Hey, I have been playing with flows and I found an odd behaviour...
Copy code
import 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
Copy code
waiting...
1A
2A
3A
kotlin.Unit
if I uncomment the
delay
the result changes
Copy code
waiting...
1A
3A
kotlin.Unit
Why is that ?
n
combine
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.
j
But we receive "3A", if that was the case, it seems that "3A" wouldn't be emitted...
n
It saves the most recent values. It’s kinda like
conflate
.