Francis Mariano
05/26/2022, 3:35 PMkable
is a great use case.
private val job = SupervisorJob(parentCoroutineContext.job)
private val scope = CoroutineScope(parentCoroutineContext + job)
private val connectionScope = CoroutineScope(scope.coroutineContext + Job(scope.coroutineContext[Job]))
Here is what I understood about the code quoted above:
scope
inherits parent's context but with new job
. That job
is a SupervisorJob
so if any child of scope
fails or is cancelled it manage each one separately (if one child fail or cancel the others child continue working and the parent also is not cancelled)
job
inherits parent's job. If parent is cancelled all the child also is cancelled.
Here is what I did not understand:
connectionScope
inherits context and job of scope
. Are they the same????travis
05/26/2022, 11:21 PMconnectionScope
will have all the same CoroutineContext
elements except its Job
will have been overwritten by the Job(parentJob)
that you did. It will essentially be a copy of scope
but with its parent being scope
. Otherwise anything that was configured previously on that CoroutineContext
such as exception handlers or dispatches, will be the same on the two scopes.
This is a great article on the topic: https://proandroiddev.com/demystifying-coroutinecontext-1ce5b68407adJob
is what is used for cancellation, so your connectionScope
will have all the same dispatchers as scope
, but you can now cancel it and it won't cancel scope
(because they have different `Job`s).connectionScope
w/ a Job
that is a child of `scope`'s Job
, if you cancel scope
then it will cancel its `Job`'s children (which means connectionScope
will also cancel in that case).Francis Mariano
05/27/2022, 11:32 AMThe Job is what is used for cancellation, so your connectionScope will have all the same dispatchers as scope, but you can now cancel it and it won't cancel scope (because they have different Jobs).
But if I cancel connectionScope
with exception different of CancellationException
so scope
is also cancelled, right???scope
does not have parentJob, so only scope
can cancel itself, ok?travis
05/30/2022, 8:30 PMscope
is configured with a parent:
https://github.com/JuulLabs/kable/blob/main/core/src/androidMain/kotlin/Peripheral.kt#L144
The parent scope is the receiver of the peripheral
extension function.
So, whenever you create a peripheral, you decide what you want the parent CoroutineScope
to be. If you cancel the scope used as the receiver of the peripheral
extension function then the `Peripheral`'s internal scope
will be cancelled.