Reputation: 53
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.
Upvotes: 0
Views: 1111
Reputation: 10523
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.
Upvotes: 2