https://kotlinlang.org logo
Title
j

jeff

11/07/2019, 6:17 PM
Hi all -- I have a Flow<> and for each item, I want to make a potentially-long-running network call. I would like these calls to happen in parallel. I can achieve that by doing
myFlow
.flatMapMerge { item ->
    flow { emit(suspendingFunctionThatMakesNetworkCall(item)) }
}
HOWEVER, Flow's flatMapMerge() has the following comment
Note that even though this operator looks very familiar, we discourage its usage in a regular application-specific flows.
Most likely, suspending operation in [map] operator will be sufficient and linear transformations are much easier to reason about.
I can't figure out how to do this with just a suspend map. Help?
o

octylFractal

11/07/2019, 7:17 PM
I'm not sure if this is really any better, but I think doing
.transform { flow -> coroutineScope { flow.map { async { suspendingFunction(it) } }.buffer(N).emitAll() } }
might work out better / be more specific
basically you launch up to N+1 concurrent async tasks, then after you can
await
and
emit
them
j

jeff

11/07/2019, 7:24 PM
interesting, let me try it