https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

azabost

09/29/2023, 9:43 PM
OK, now this drives me nuts. Why doesn't it print anything and deadlocks at
flow.emit(1)
?
Copy code
fun main() = runBlocking {
    val flow = MutableSharedFlow<Int>()
    
    launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        flow.onEach { println(it) }.first()
    }

    flow.emit(1)
}
e

ephemient

09/29/2023, 9:44 PM
the launched coroutine is still running so the parent scope is kept alive
a

azabost

09/29/2023, 9:45 PM
I know it's running, but why doesn't it print
1
?
e

ephemient

09/29/2023, 9:47 PM
the emit happens before the collector starts
which means it's dropped
a

azabost

09/29/2023, 9:48 PM
aaahhh
e

ephemient

09/29/2023, 9:48 PM
Copy code
launch(<http://Dispatchers.IO|Dispatchers.IO>, start = CoroutineStart.UNDISPATCHED) {
    flow.onEach { println(it) }.first()
}
will happen to wait for the collector to suspend before
launch
proceeds
(has other potential side-effects so it's not always the right thing to do, but in this case…)
a

azabost

09/29/2023, 9:49 PM
you are totally right
OMG, I guess it's getting too late
Thanks a lot 🍻
2 Views