if your scope launches more than one coroutine, and say you have a specific coroutine that you might wanna cancel, keeping a reference to a job is the way to go.
If its just one job running in the scope, canceling the scope has the same effect.
Another difference is, when you cancel a job in a scope, you can still launch other coroutines from that scope. But if you do cancel the scope, you won't be able to launch other coroutines afterwards
e
efemoney
08/05/2020, 9:57 AM
Its important to note that cancelling a scope is the same thing as cancelling the
Job
element in that scope’s
CoroutineContext
and that job is the parent of all the jobs for all the coroutines launched within that scope. At the end of the day the rules of job cancellation still apply to the scope(’s
Job
)
b
bdawg.io
08/07/2020, 5:20 AM
These two snippets are identical in effect.
Copy code
val job = Job()
val scope = CoroutineScope(job)
for (i in 1..100_000) scope.launch { ... }
job.cancel()
vs
Copy code
val scope = CoroutineScope(Job())
for (i in 1..100_000) scope.launch { ... }
scope.cancel()