Launch doesn't start a coroutine if in an infinite loop

I found no coroutine will be started in below code:

runBlocking {
            while (true) {
                launch {
                    println("hello world")
                }
            }
}

not a single “hello world” will be printed in the above example, however, simply moving the runBlocking into the while loop works:

            while (true) {
               runBlocking {
                   launch {
                      println("hello world")
                   }
              }
            }

Can somebody explain the reason? Thank you!

1 Like

interesting…

I always thought suspend fun main was just short for fun main = runBlocking{}

however:

fun main(){
    runBlocking {
        coroutineScope {
            while (true) launch {
                println("hello world")
                delay(1)
            }
        }
    }
}

doesn’t work and with suspend fun main it does…

suspend fun main(){
    coroutineScope {
        while (true) launch {
            println("hello world")
            delay(1)
        }
    }
}

launch() will schedule the coroutine to run on the current thread (the thread that is performing an infinite loop) if you don’t specify a different dispatcher. But in order for the scheduled coroutine to run, the current coroutine (the one created by runBlocking()) has to suspend. That allows the current thread to run other coroutines scheduled on it. A coroutine created with runBlocking() will suspend when it gets to the end, which is why your second example works. But in your first example, the outer coroutine created by runBlocking() never suspends – it just creates coroutine after coroutine, scheduling them on a thread which will never be allowed to run them.

2 Likes