2

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?

dumbfingers
  • 7,001
  • 5
  • 54
  • 80
  • Please also read this question and answer which explains further: https://stackoverflow.com/questions/59368838/difference-between-coroutinescope-and-coroutinescope-in-kotlin – dumbfingers Apr 22 '20 at 09:25

1 Answers1

1

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Thanks. Now I understand the differences. But why the former don't print anything? If it sets up a scope just for the `launch`, then it should run the function to print? – dumbfingers Apr 03 '20 at 15:40
  • 1
    Because your whole program ends before it has got its chance to print. – Marko Topolnik Apr 03 '20 at 19:32