'CoroutineScope launch work well inside direct call, but inside parameter scope launch, not working
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
