Today I found there are two functions in coroutine...
# coroutines
a
Today I found there are two functions in coroutine package;
coroutineScope
or
supervisorScope
. When should we use it instead of using
CoroutineScope(SupervisorJob())
? How do we cancel
coroutineScope
or
supervisorScope
?
g
Have you checked documentation of those functions?
They are very supervisorScope and
CoroutineScope(SupervisorJob())
are very different. First is suspend function that suspend until all child coroutines are finished, second is creation of new object scope that you have to manage manually
How do we cancel
coroutineScope
or
supervisorScope
?
As any other suspend function, cancel coroutine where this suspend function invoked
z
coroutineScope
and
supervisorScope
will also share the same context as the caller (they just replace the Job), so eg the same dispatcher will be used for coroutines launched inside them.
CoroutineScope()
will have an otherwise empty context, containing only the Job. The former calls will also create jobs that are children of the caller's job, so if the caller is cancelled any coroutines launched inside them will also be cancelled. The latter creates a "root" job so you might leak coroutines.
CoroutineScope(coroutineContext + SupervisorJob(parent = coroutineContext[Job]))
is closer, although it still won't automatically join on any new coroutines as Andrey pointed out.