kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

Consider marking `runBlocking` as `@DelicateCoroutinesApi`

Open joffrey-bion opened this issue 1 year ago • 4 comments
trafficstars

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:

  • https://github.com/Kotlin/kotlinx.coroutines/issues/2448
  • https://github.com/Kotlin/kotlinx.coroutines/issues/3982
  • https://github.com/Kotlin/kotlinx.coroutines/issues/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.

joffrey-bion avatar Oct 04 '24 10:10 joffrey-bion