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
coroutineScope
is 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 aCoroutineScope
and sincelaunch
is an extension function onCoroutineScope
, it is valid.The names are actually a bit confusing.
coroutineScope
is a function which takes a suspending lambda withCoroutineScope
as the receiver whileCoroutineScope(context)
is a function which creates a CoroutineScope.coroutineScope
is generally used to capture the currentcoroutineContext
inside a suspend function. For example,Using
coroutineScope
has this advantage that the coroutines launched inside will get cancelled when the parent coroutine cancels.