Is there any difference beween calling `.cancel()`...
# coroutines
l
Is there any difference beween calling
.cancel()
on the job of the scope VS calling
.cancel()
on the scope itself? Lots of blogpost recommend to keep a reference to the
job
in order to be able to cancel it, although IMO this is not necessary, as cancelling the scope itself has the exact same effect. Am I correct?
t
i always go with the scope because it feels like a composite disposable from RX land. though sometimes its cancel children instead of cancel
rarely did I ever track individual disposables in years of using RX. I expect coroutine jobs to be the same
☝️ 1
e
It’s only a matter of (for lack of better word) scope 🙂_._ The scope(’s
Job
) might contain more coroutines than the individual job, which represents a subtree of coroutines in the wider scope’s tree of coroutines.
😂 1
☝️ 1
o
a
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
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
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()