https://kotlinlang.org logo
Title
m

Mauricio Barbosa

01/19/2020, 4:52 PM
Hi guys, Can someone help me understand what’s going on with this code? I’m trying to create a flow that merge the responses of some requests and emit a new value every time a response is retrieved. For some reason this code crashes after the first request, printing the following log:
Doing first request
retrieving first request
Exception in thread "main" kotlinx.coroutines.JobCancellationException: Parent job is Completed; job=ScopeCoroutine{Completed}@383534aa
Has someone any ideia of what am I doing wrong?
a

Adam Powell

01/19/2020, 4:57 PM
Switch
coroutineScope
and
flow
in your nesting at the beginning of
composedRequest()
. You want the flow to have a scope, you don't want to have a scope for constructing the flow.
The exception is because the
coroutineScope
is completed by the time
composedRequest
returns the new flow object, so when you
collect
it you're trying to use
async
to launch child coroutines of a parent that isn't active anymore
m

Mauricio Barbosa

01/19/2020, 5:18 PM
Hi Adam, Thanks for replying. I think I understand what’s going on. But I still need a scope in order to use the
async
inside flow. So, what’s the correct approach? Can I encapsulate
async
inside a
coroutineScope
?
a

Adam Powell

01/19/2020, 5:20 PM
You should swap the positions of the
coroutineScope
and the call to
flow {}
And you can drop
suspend
from
composedRequest
m

Mauricio Barbosa

01/19/2020, 5:36 PM
It works! Thanks @Adam Powell
👍 1