Differences between two coroutine launch in kotlin

Viewed 177

What's the difference between CoroutineScope(dispatchers).launch{} and coroutineScope{ launch{}}?

Say I have the code below:

(you can go to Kotlin playground to run this snippet https://pl.kotl.in/U4eDY4uJt)

suspend fun perform(invokeAfterDelay: suspend () -> Unit) {
    // not printing
    CoroutineScope(Dispatchers.Default).launch {
        delay(1000)
        invokeAfterDelay()
    }


    // will print
    coroutineScope {
        launch {
            delay(1000)
            invokeAfterDelay()
        }
    }
}

fun printSomething() {
    println("Counter")
}


fun main() {
    runBlocking {
        perform {
            printSomething()
        }
    }

}

And as the comment stated, when using CoroutineScope().launch it won't invoke the print, however when using the other way, the code behaves as intended.

What's the difference?

Thanks.

Further question

New findings.

if I leave the perform function like this (without commenting out one of the coroutines)

suspend fun perform(invokeAfterDelay: suspend () -> Unit) {

        CoroutineScope(Dispatchers.Default).launch {
            delay(1000)
            invokeAfterDelay()
        }

        coroutineScope {
            launch {
                delay(1000)
                invokeAfterDelay()
            }
        }

    }

then both of these coroutines will be executed Why?

1 Answers

CoroutineScope().launch {} and coroutineScope { launch{} } have almost nothing in common. The former just sets up an ad-hoc scope for launch to run against, completing immediately, and the latter is a suspendable function that ensures that all coroutines launched within it complete before it returns.

The snippet under your "Further question" is identical to the original one except for the deleted comments.

Whether or not the first coroutine prints anything is up to non-deterministic behavior: while perform is spending time within coroutineScope, awaiting for the completion of the inner launched coroutine, the first one may or may not complete itself. They have the same delay.

Related