I have a 'parent' `CoroutineScope` which has a lon...
# coroutines
w
I have a 'parent'
CoroutineScope
which has a long lifecycle. I want to make another scope which has a shorter lifecycle (potentially several in the same span as the 'parent'). If the parent scope is cancelled I want both parent and the shorter lifecycle scope to be cancelled as far as i can tell you can't inherit scopes like this. another (seemingly bad) idea I have is to maintain a collection of `Job`s for the shorter lifecycle group, which will allow me to cancel everything in that collection, or if the parent scope is cancelled, they would all be launched under it anyway, and get cancelled
j
as far as I can tell you can't inherit scopes like this
You can create such a child scope by creating it with an explicit job that has the job from the parent scope as parent:
CoroutineScope(Job(parent = parentScope.job))
(I think there is a
.job
extension property like this on the coroutine scope)
Otherwise if you use regular coroutine builders in the parent scope you automatically get a child scope inside them:
Copy code
parentScope.launch { // this = child scope
   ...
}
z
Yea, you can definitely do this, this is the core idea behind structured concurrency
w
Thanks @Joffrey i'll give that a try
haven't tested it yet but I could access the job through
parentScope.coroutineContext.job
thanks again joffrey. seems to be working great after testing. of course the
launch
example is obvious with normal structured concurrency. didn't realize i could do this to jobs though
j
You're welcome ☺️ Yeah the job gymnastics is not advertised that much. The important thing to keep in mind is that the part that is responsible for structured concurrency is in fact the job, not the scope per se
☝🏻 1
w
yeah makes sense. i didn't realize the scope maintained a job like that. perhaps i should read a bit more on that