Is there anything particularly special with vmScop...
# coroutines
a
Is there anything particularly special with vmScope.coroutineContext? When I use CoroutineScope(job + vmScope.coroutineContext) to launch coroutine and use job.cancel() it doesn't cancel the coroutine. This is an example https://pl.kotl.in/e0WxVRCBt which is able to cancel with another context in place of vmScope.coroutineContext
b
vmScope.coroutineContext have a Job too, and when you're doing CoroutineContext+CoroutineContext is not symmetric, so if both contexts have an element of the same type (in your example it's Job) the one from the second context wins. So you need to use
Copy code
vmScope.coroutineContext + job
to get it working.
But note, that now once you cancel vmScope, anything launched with
job
won't be canceled. To make it working you need to define Job's parent<->child relation:
Copy code
val job = Job(vmScope.coroutineContext.job) // now new Job is a child of job from vmScope
val newScope = CoroutineScope(vmScope.coroutineContext + job)
a
Let me try and check both scenarios to see the difference.
I tested
vmScope.coroutineContext + job
first, found that job wasn't cancelled when vmScope is cleared. Then with
Copy code
val job = Job(vmScope.coroutineContext.job) // now new Job is a child of job from vmScope
val newScope = CoroutineScope(vmScope.coroutineContext + job)
the job is cancelled on job.cancel and when vmScope is cleared. Thanks!
I see that with the new approach, this also works and correct?
Copy code
val job = Job(vmScope.coroutineContext.job) // now new Job is a child of job from vmScope
val newScope = CoroutineScope(job)
b
kinda, you will loose other elements from the original context (typically Dispatcher, but also maybe CoroutineExceptionHandler/CoroutineName/ThreadLocal element etc)
👍 1