Canceling the outermost coroutine wouldn’t cancel the produce job, because the directly passed
SupervisorJob
has no parent?
Correct
So the coroutine created by
withContext
fails with the exception, because its Job is canceled by the failingproduce
coroutine, which passes the exception tocancel
?
Mostly correct, it’s not cancel
, it’s a childCancelled
internal method
It wasn’t clear to me that
withContext
creates another job. Is this information missing in the documentation or is this implicit by some other statement?
No, withContext is not clear about this at all (IMO), but CoroutineScope is helpful:
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html
Is
withContext(coroutineContext){}
semantically the same ascoroutineScope{}
?
As far as I’m aware, yes. They are intended for different use cases, docs make purpose of each pretty clear, I think.
Anyway here is my new attempt
Is it closer to the original this time
On the surface, supervisorScope is not an extension method, and it handles any Throwable, not just Exception. As far as a being a Structured Concurrency learning exercise, it looks pretty good to me. Let’s stick with what the experts created for us in our real code, though