Reputation: 39
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")
}
}
Upvotes: 3
Views: 546
Reputation: 17288
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).
Upvotes: 4