How to create a `CoroutineScope` that is a child of another ? What I tried: ```val parentScope = ......
t
How to create a
CoroutineScope
that is a child of another ? What I tried:
Copy code
val parentScope = ...
val childScope = parentScope + SupervisorJob()

parentScope.cancel()
parentScope.isActive // false
childScope.isActive // true (!!)
It seems that cancelling the parent does not cancel its children. I guess I'm missing something here...
b
val childScope = parentScope + SupervisorJob(parentScope.coroutineContext[Job])
it attaches child job to parent job
j
Woudln't this make them siblings rather than enforce a parent-child hierarchy?
d
Isn't it just either
coroutineScope
(doc) or
supervisorScope
(doc)
Well this doesn't return the scope to you, right.
b
@Javier Troconis nope, it will be parent-child hierarchy, if you cancel childScope, parentScope will be active active. From the SupervisorJob doc:
* If [parent] job is specified, then this supervisor job becomes a child job of its parent and is cancelled when its parent fails or is cancelled. All this supervisor's children are cancelled in this case, too. The invocation of [cancel][Job.cancel] with exception (other than [CancellationException]) on this supervisor job also cancels parent.
👍 1
j
Thanks @bezrukov. Thought that it was simply setting the job itself and not the parent
t
Indeed, that was the missing part! I expected the child scope to directly inherit the job of its parent. It seems that this parent-child relationship should be explicitly defined
b
I think it's impossible because constructor can't be suspend, and there is no access to coroutineContext from non-suspend block.