I was messing around with launching coroutines ins...
# coroutines
t
I was messing around with launching coroutines inside an async parent coroutine and the effects on their completion when cancelling that parent scope. I wanted to see could they still be cancelled early if passed as a lambda to a function that would wrap them in a parent coroutine. Doesn't seem to work as I expected. Here's a gist - https://gist.github.com/Munzey/212f38879039987a4c819c53d1d393cd maybe its just something one should never do, but maybe someone can explain to me why it doesn't work the way I thought it would 🙂 cheers!
m
The name
parentScope
is confusing. You’re passing the child, not the parent.
It works as expected.
coroutineScopeWrapper
returns immediately because two two
launch
are executed in the real parent scope of
runBlocking
and thus the scope of
async
doesn’t need to wait for them.
🙇‍♂️ 1
t
oh my bad maybe I'm misunderstanding. In my head when I call the
async
builder, that is the "parent" coroutine, and so from there im passing that down
m
runBlocking
is the topmost scope.
coroutineScope
is a child of
runBlocking
(more or less).
async
is a child of
coroutineScope
. And the launch in your wrapper use the
CoroutineScope
of
runBlocking
so they’re direct children of it.
👍 1
launch
basically means
this@runBlocking.launch
in your example.
Nonetheless,
cancel()
doesn’t cancel. WTF 😄
t
Thanks for this explanation, really helpful! I thought that
coroutineScope
provides a different Job and that the launches were "tied" to it, but I guess they still have the same context which is runBlocking? So to make this cancel the way I expect, would I need to define a new scope in
coroutineScopeWrapper
instead?
m
launch
is tied to it. But you don’t give the
launch
invocation the
CoroutineScope
of the
async
.
I’ve added another comment.
t
ah thanks a lot 🙂