Kotlin coroutine val vs fun

I am a new student at coroutine and Kotlin. Why am I getting different results, examples 1 and 2 below?

fun main(args: Array<String>) = runBlocking {
    fun a() = async(CommonPool) {
        println("start A")
        delay(1000)
        println("finish A")
    }

    fun b() = async(CommonPool) {
        println("start B")
        delay(1000)
        println("finish B")
    }

    //case 1
    a().await()
    b().await()

    //case 2
    val A = a()
    val B = b()
    A.await()
    B.await()
}

      

Is this basic val style coding?

+3


source to share


1 answer


Case 1 is equivalent

val A = a()
await(A)
val B = b()
await(B)

      



That is, you start A

, wait for it (the coroutine pauses here), and only then do you start B

, so A

they B

are executed sequentially, not simultaneously.

In case 2, you run both A

and B

and only then does the coroutine suspend the waits A

and B

.

+11


source







All Articles