What is the execution order of suspended functions?

I am puzzled by how code with coroutines is executed:

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() {
    runBlocking {
        launch {
            println("main:Do A")
            doA()
            println("main:A is done")
            println("main:Do B")
            doB()
            println("main:B is done")
        }
    }
}

suspend fun doB() {
    println("suspended:Doing A")
    delay(1000)
}

suspend fun doA() {
    println("suspended:Doing B")
    delay(1000)
}

Output:

main:Do A
suspended:Doing B
main:A is done
main:Do B
suspended:Doing A
main:B is done

The order or invocations is very confusing. How is it possible that after main:Do A we jump right into second suspend function. Is there a way to see how this code is transformed, or would look like in java?

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() {
    runBlocking {
        launch {
            println("main:Do A")
            doA()
            println("main:A is done")
            println("main:Do B")
            doB()
            println("main:B is done")
        }
    }
}

suspend fun doA() {
    println("suspended:Doing A")
    delay(1000)
}

suspend fun doB() {
    println("suspended:Doing B")
    delay(1000)
}

You’ve got your functions named the wrong way around (or equivalently, you’ve got the println("suspended:Doing X") the wrong way around), that’s all :smiley:

2 Likes

cool story, insane!

2 Likes