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
bezrukov
01/26/2022, 4:06 PM
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.
bezrukov
01/26/2022, 4:08 PM
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
Arun Joseph
01/26/2022, 4:09 PM
Let me try and check both scenarios to see the difference.
Arun Joseph
01/26/2022, 5:06 PM
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!
Arun Joseph
01/26/2022, 5:12 PM
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
bezrukov
01/26/2022, 5:15 PM
kinda, you will loose other elements from the original context (typically Dispatcher, but also maybe CoroutineExceptionHandler/CoroutineName/ThreadLocal element etc)