Charles
Charles

Reputation: 173

coroutineScope start first than launch

I'm studying coroutine, and writing some examples, I found some weird things. even if I write the launch build first, it start late than coroutineScope. I understand coroutineScope has a suspending point. Is there any one who explain this?

below is my code

import kotlinx.coroutines.*

fun main() = runBlocking {

    launch {
        println("Start")
    }

    coroutineScope {
        launch {
            delay(1000)
            println("World!")
        }

        println("Hello")
    }

    println("Done")

/*    
    expected

    Start
    Hello
    World!
    Done
    
    result

    Hello
    Start
    World!
    Done
 */
}

Upvotes: 0

Views: 1023

Answers (1)

Arpit Shukla
Arpit Shukla

Reputation: 10523

launch block isn't executed immediately. It is sort of scheduled for asynchronous execution and the function returns immediately. That's why "Start" is not printed immediately and the control moves inside the coroutineScope. You can verify this with a simple example like:

launch {
    println("Start")
}
println("End")

Here you will see that End is printed before Start

Upvotes: 1

Related Questions