From the documentation of runBlocking
is it clear why it does not make sense to use it from a coroutine, e.g., nest it.
It even explicitly states:
This function should not be used from a coroutine.
However, it is possible to do so:
fun main(args: Array<String>) {
runBlocking {
runBlocking {
println("hi")
}
}
}
The (IntelliJ) IDE complains a bit
but the code compiles and runs.
What can happen when done accidentally in a more complex setting? Crashes? Or maybe Deadlocks?
What can happen when done accidentally in a more complex setting? Crashes? Or maybe Deadlocks?
No, nothing like that. In fact, runBlocking
is specifically written to support nesting:
If the specified dispatcher is an event loop of another
runBlocking
, then this invocation uses the outer event loop.
The concern you mention is not actually related to nesting runBlocking
calls, but a general concern of calling any blocking code from a coroutine. We use coroutines with the specific purpose of avoiding to block the thread, so it's usually an error to call blocking functions inside them. You'll get the same warning for Thread.sleep()
, java.io
calls etc.
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