Why will this code never print Hello World?
runBlocking(Dispatchers.Main) {
launch {
delay(1)
println("Hello world")
}
}
But this will print
runBlocking {
launch {
delay(1)
println("Hello world")
}
}
From what I see first example outright freezes the app (when used inside a button click listener).
The issue is you're causing a deadlock:
Dispatchers.Main works by posting (dispatching) coroutines to main application looperrunBlocking blocks the main application threadrunBlocking to finishYou can slightly alleviate the "issue" by using Dispatchers.Main.immediate instead which is a little smarter version of base dispatcher - it doesn't post coroutine to main looper if it's already running on the main thread and executes it in-place.
This will allow you to run the launch block, however delay will once again post coroutine to continue on main looper and cause another dead lock.
Second code sample has no issues since coroutines running there do not interact with main thread (aside from runBlocking it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With