Can someone explain me why the second child is not cancelled?
Copy code
coroutineScope {
launch {
if (condition) cancel() // does not cancel the coroutine of flow
}
launch {
dataSource.channel.receiveAsFlow() {
.collect { doSomething() }
}
}
I would expect that cancelling first coroutine would cancel second coroutine but it doesn't. Any ideas?
l
louiscad
03/29/2021, 9:20 AM
It'd if it crashed (i.e. you throw a non
CancellationException
), but I guess what you're looking for here is doing
this@coroutineScope.cancel()
.
a
Albert Chang
03/29/2021, 9:39 AM
The reason is that
launch
will create a new
CoroutineScope
for the job which is different from the outer scope. You are canceling the inner scope so it won't affect other jobs in the outer scope.
💯 2
l
Lilly
03/29/2021, 9:44 AM
@Albert Chang hmm but
coroutineScope
states: "When any child coroutine in this scope fails, this scope fails and all the rest of the children are cancelled". My example macthes this statement exactly, not?
a
Albert Chang
03/29/2021, 9:46 AM
@Lilly "fails" means throwing exception other than