parallel Map
Like map, but runs transform for many elements at the same time. The results keep the input order.
Example
val profiles = userIds.parallelMap(concurrency = 8) { id ->
api.fetchProfile(id)
}
// profiles[i] belongs to userIds[i], whatever order the calls end in.How it runs
At most concurrency calls run at the same time. A large input does not start one coroutine per element: a fixed group of concurrency coroutines takes the elements in order.
The first failure cancels the other calls, and
parallelMapthrows it.parallelMapcopies the elements before it starts. A later change to the source collection does not change the result.
Cancellation
When the caller is cancelled, every running call is cancelled before the cancellation is thrown.
Watch out
The default concurrency has no limit. For network or disk work, pass a limit.
The calls run on the dispatcher of the caller. For blocking calls, wrap the work in
withContext(ioDispatcher).
Parameters
the largest number of calls that run at the same time. At least 1. The default, Int.MAX_VALUE, means no limit.
See also
Throws
if concurrency is less than 1.