Home > Mobile >  How to understand Coroutine Process with Example in kotlin
How to understand Coroutine Process with Example in kotlin

Time:11-10

I'm studying coroutine with docs and some examples. testing some examples, I found that in same CoroutineScope it works sequentially. For example Below code is working sequentially.

fun main() = runBlocking {
    coroutineScope {
        launch {
            delay(1000)
            println("Start")
        }
    }

    coroutineScope {
        launch {
            delay(2000)
            println("World2")
        }

        launch {
            delay(1000)
            println("World1")
        }

        println("Hello")
    }

    println("Done")

}

/*
Start
Hello
World1
World2
Done
*/

But If I change above codes like this

fun main() = runBlocking {
    launch {
        delay(1000)
        println("Start")
    }

    coroutineScope {
        launch {
            delay(2000)
            println("World2")
        }

        launch {
            delay(1000)
            println("World1")
        }

        println("Hello")
    }

    println("Done")

}

/*
Hello
Start
World1
World2
Done
*/

Removing first CoroutineScope, the result sequence is changed. In My Opinion, I think this is a problem of job state, but not sure. Is there anyone who can clarify this issue?

CodePudding user response:

coroutineScope suspends until all its children coroutines have finished their execution. In your first case, the coroutineScope waits until the launch completes and prints Start, that's why you see Start as the first output on console.

In the second part, you removed the coroutineScope, so now it just launches a new coroutine and moves to the next step (launch doesn't suspend). Then in the coroutineScope you launch two other coroutines (using launch) and print Hello. That's why the Hello gets printed first. All other print statements are waiting for the delay to finish.

After 1 second, the first launch completes and prints Start followed by World1 and World2. Now when this coroutineScope finishes, the program control moves to the final print statement and prints Done.

  • Related