Search code examples
androidkotlinkotlin-coroutines

How does the code work when “run blocking” is used?


private fun runBlockingWithLaunch() {
    print(1)
    runBlocking {
        print(2)
        launch {
            print(3)
            delay(2_000)
            print(4)
        }
        print(5)
    }
    print(6)
}

When I ran the code above, I was expecting an answer of 123546, but I got an answer of 125346.

Can someone tell me why he's working like this?

I also tried the following variations and the answers changed when I changed the “delay” I just added

private fun runBlockingWithLaunch() {
    print(1)
    runBlocking {
        print(2)
        launch {
            delay(1) //new
            print(3)
            delay(2_000)
            print(4)
        }
        delay(2) //new
        print(5)
    }
    print(6)
}

result ->125346

private fun runBlockingWithLaunch() {
    print(1)
    runBlocking {
        print(2)
        launch {
            delay(1) //new
            print(3)
            delay(2_000)
            print(4)
        }
        delay(3) //new
        print(5)
    }
    print(6)
}

result-> 123546


Solution

  • runBlocking establishes a single-thread dispatcher within current thread to run suspending code.

    launch usually launches an asynchronous coroutine but in this context it just ends up deferred as "runblocking dispatcher" is occupied by code in runblockings body.

    Adding delays (suspension points) frees the dispatcher up allowing the execution to "jump" around between competing coroutines.