How to understand order of calling coroutines with scope?

Viewed 236

I saw the coroutines example here.

To understand the example I made three different examples with each scope.
The printed number is the following #N.
It's just my opinion, so if there is a wrong thing, let me know.

#1: 3->1->2->4

runBlocking {
    launch {
        println("1-Task from runBlocking")
    }

    coroutineScope { // Creates a coroutine scope
        launch {
            println("2-Task from nested launch")
        }

        println("3-Task from coroutine scope")
    }

    println("4-Coroutine scope is over") 
}

I understood the coroutineScope waits until the children will be completed. The outer runBlocking has two coroutines. The first is launch of 1 and the second is in coroutineScope. The coroutineScope will be handled first based on the call stack. Thus the first printed number is 3 because it's within regular function. And then the 1 can be printed before 2. The 4 will be printed after coroutineScope block is finished.

#2: 1->3->2->4

runBlocking {
    launch {
        println("1-Task from runBlocking")
    }

    runBlocking { // Creates a coroutine scope
        launch {
            println("2-Task from nested launch")
        }

        println("3-Task from coroutine scope")
    }

    println("4-Coroutine scope is over")
}

runBlocking is not suspend function that's why the outer runBlocking doesn't have a coroutine.
Thus the 1 will be printed first. After that, the inner runBlocking has one coroutine so wait until this block will be finished.
Thus 3 and 2 will be printed. Last, 4 printed after inner runBlocking.

#3: 2->4->3->1, 4->3->2->1, 4->2->3->1

runBlocking {
    launch {
        println("1-Task from runBlocking")
    }

    GlobalScope.launch { // Creates a coroutine scope
        launch {
            println("2-Task from nested launch")
        }

        println("3-Task from coroutine scope")
    }

    println("4-Coroutine scope is over") 
}

There are several different results so I guessed it depends on environments on runtime.
But I wonder if it's impossible to print 1 first or not.
Second, how to understand scope in other suspend or scope.

0 Answers
Related