Description
From the runBlocking documentation:
It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests
Part of this is obsolete now. We have suspend fun main
to get a suspending context right from the entrypoint. We have kotlinx-coroutines-test
for tests.
This leaves the "briding" use case as the remaining valid case for runBlocking
, but this is quite general/vague and runBlocking
is still dangerous in many such cases. We have already seen a few nasty cases where runBlocking
is synonym for trouble:
- runBlocking with Android's Main.immediate scheduler locks with other nested contexts #2448
- Nested
runBlocking
deadlocks when a task depends on the nestedrunBlocking
itself #3982 runBlocking
executes other tasks instead of its own #4215
My intuition is that we should only use runBlocking
when we have no other choice, and that there aren't many cases where runBlocking
is the only choice (and is safe). In that sense, I believe it would be a net positive to mark runBlocking
as @DelicateCoroutinesApi
, with an updated doc to explain more details.
It would be worth documenting the cases that are safe for runBlocking
, and the cases for which we know better alternatives. A bit like what was done for GlobalScope
.