https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

David Glasser

05/26/2020, 9:35 PM
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

bezrukov

05/26/2020, 9:53 PM
there is
concurrency
param in flatMapMerge
d

David Glasser

05/26/2020, 9:55 PM
@bezrukov but flatMapMerge doesn’t preserve order, right?
b

bezrukov

05/26/2020, 9:55 PM
yes
d

David Glasser

05/26/2020, 9:56 PM
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

bezrukov

05/26/2020, 10:03 PM
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

Dominaezzz

05/26/2020, 11:12 PM
Or use a
Semaphore
!
3 Views