I have a List<I> and a mapping function `sus...
# coroutines
d
I have a List<I> and a mapping function
suspend (I)->O
. I’d like to get the
List<O>
out, running a bounded number of copies of the mapping function in parallel. I feel like this should be straightforward, eg with Flow, but I can’t quite get it to work
eg, it’s not
in.asFlow().buffer(N).map(f)
or
in.asFlow().flatMapMerge{ flow { emit (f(it)) } }
I guess there’s
Copy code
map { async { f(it) } }.awaitAll()
which seems “unbounded” but that’s fine i suppose
b
there is
concurrency
param in flatMapMerge
d
@bezrukov but flatMapMerge doesn’t preserve order, right?
b
yes
d
yeah, i do want to preserve order, so flatMapMerge is no good.
(i mean i can do some sort of flatMapMerge with indices and sort at the end I guess but that seems overkill)
b
you can create dispatcher with your concurrency level and then use
Copy code
map { async(yourDispatcher) { f(it) } }.awaitAll()
but it looks like overkill as well. there was a ticket for re-implementation fixedThreadPoolContext to avoid creation real dispatcher, but there is no eta.
d
Or use a
Semaphore
!