Using coroutineScope function vs passing CoroutineScope as argument

454 Views Asked by At

Using coroutineScope in a suspend function that will be called from a CoroutineScope, is it giving the same result as passing that CoroutineScope as a parameter to the suspend function ?

import kotlinx.coroutines.coroutineScope

suspend fun loadContributorsConcurrent() {
    coroutineScope {
        // launch...
    }
}
suspend fun loadContributorsConcurrent(outerScope: CoroutineScope) {
    outerScope.run {
        // launch...
    }
}
2

There are 2 best solutions below

0
Louis Wasserman On

No. In the second version, you can pass a scope that does not match the scope in which loadContributorsConcurrent is actually run. The use of run makes things even worse, as code will usually be run in the correct scope except launch or async coroutines.

The first pattern is the correct one.

0
Linus Lindgren On

The code in your second proposal has a major flaw, it does not suspend. Meaning that if you were to launch on the injected scope, it would launch an asynchronous job.

I have not yet seen a use-case for injecting the scope, I'd opt for a suspending function, in your case the first option.