CoroutineScope launch work well inside direct call, but inside parameter scope launch, not working

1k views Asked by At
fun test(coroutineScope: CoroutineScope){
        coroutineScope.launch {
            //FUNC 1
        }

        CoroutineScope(Dispatchers.XXX).launch {
            //FUNC 2
        }
    }

FUNC 1 Not working but FUNC 2 is work well!

I don't know the difference between the two.

1

There are 1 answers

1
Arpit Shukla On BEST ANSWER

This is because coroutineScope is a function which returns whatever the lambda block returns. And since it is a function, you need to invoke it like coroutineScope(block = { ... }) or coroutineScope { ... }. While in your 2nd case, CoroutineScope(Dispatchers.XXX) returns a CoroutineScope and since launch is an extension function on CoroutineScope, it is valid.

The names are actually a bit confusing. coroutineScope is a function which takes a suspending lambda with CoroutineScope as the receiver while CoroutineScope(context) is a function which creates a CoroutineScope.

coroutineScope is generally used to capture the current coroutineContext inside a suspend function. For example,

suspend fun uploadTwoFiles() {
    // Here we need to launch two coroutines in parallel, 
    // but since "launch" is an extension function on CoroutineScope, 
    // we need to get that CoroutineScope from somewhere.
    coroutineScope {
        // Here we have a CoroutineScope so we can call "launch"
        launch { uploadFile1() }
        launch { uploadFile2() }
    }
    // Also, note that coroutineScope finishes only when all the children coroutines have finished.
}

Using coroutineScope has this advantage that the coroutines launched inside will get cancelled when the parent coroutine cancels.