https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Lukas Lechner

08/05/2020, 6:55 AM
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

trevjones

08/05/2020, 6:57 AM
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

efemoney

08/05/2020, 6:59 AM
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

octylFractal

08/05/2020, 6:59 AM
a

andylamax

08/05/2020, 9:53 AM
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()
4 Views