Aldo Wachyudi
08/05/2019, 2:39 AMcoroutineScope
or supervisorScope
. When should we use it instead of using CoroutineScope(SupervisorJob())
? How do we cancel coroutineScope
or supervisorScope
?gildor
08/05/2019, 2:41 AMCoroutineScope(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 manuallyHow do we cancelAs any other suspend function, cancel coroutine where this suspend function invokedorcoroutineScope
?supervisorScope
Zach Klippenstein (he/him) [MOD]
08/05/2019, 3:50 PMcoroutineScope
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.