API_1024
API_1024

Reputation: 589

Sequential coroutines in Kotlin

I'm trying to understand how sequential coroutines work in Kotlin.

The next sample will run them sequentially:

fun main(): Unit = runBlocking {
    launch {
        delay(1000) // Note the delay
        println("A")
    }.join()

    launch {
        println("B")
    }.join()
}

Being the result, "A"-->"B"

But when running next, the result is "B"-->"A", which is what I can't understand:

fun main(): Unit = runBlocking {

    val jobA = launch {
        delay(1000)
        println("A")
    }

    val jobB = launch {
        println("B")
    }

    jobA.join()
    jobB.join()
}

As I'm calling jobA.join() first, I would had thought it would wait until completes before executing jobB, regardless if jobA calls a delay. What would be the explanation for this? And how can then jobs instances be executed sequentially with delays inside?

Upvotes: 1

Views: 431

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200138

In your second example, you launched two coroutines that go on executing concurrently. After that, your top-level coroutine awaits for the first coroutine to complete, and then for the second one. Awaiting on the completion of concurrent coroutines does not interfere with their execution.

Therefore, the coroutines execute as programmed to do, the first one printing after a delay and the second one printing immediately.

Upvotes: 1

Related Questions