0

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...
    }
}
Ismaïl
  • 60
  • 1
  • 7
  • Does this answer your question? [Should you pass coroutineScope as function argument?](https://stackoverflow.com/questions/61606630/should-you-pass-coroutinescope-as-function-argument) – tornadoradon Mar 25 '23 at 16:17
  • No, in the first, coroutines launched from within are children and it will wait for them. In the second, the launched coroutines will be siblings and will not be waited for. – Tenfour04 Mar 25 '23 at 16:35
  • @tornadoradon Not really, I saw that question before posting mine, I'm not really asking about the difference between passing a **CoroutineScope** as argument or creating an **extension function** for it. I want to know the difference between passing **CoroutineScope** as an argument or creating a new nested one with `coroutineScope` function – Ismaïl Mar 25 '23 at 18:05

2 Answers2

0

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

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.