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.
This is because
coroutineScopeis a function which returns whatever the lambda block returns. And since it is a function, you need to invoke it likecoroutineScope(block = { ... })orcoroutineScope { ... }. While in your 2nd case,CoroutineScope(Dispatchers.XXX)returns aCoroutineScopeand sincelaunchis an extension function onCoroutineScope, it is valid.The names are actually a bit confusing.
coroutineScopeis a function which takes a suspending lambda withCoroutineScopeas the receiver whileCoroutineScope(context)is a function which creates a CoroutineScope.coroutineScopeis generally used to capture the currentcoroutineContextinside a suspend function. For example,Using
coroutineScopehas this advantage that the coroutines launched inside will get cancelled when the parent coroutine cancels.