mapAsync

fun <T, R> Flow<T>.mapAsync(concurrency: Int, transform: suspend (T) -> R): Flow<R>

Like map, but runs up to concurrency calls of transform at the same time. The output keeps the input order.

urls.asFlow()
.mapAsync(concurrency = 4) { download(it) }
.collect { save(it) }
// Four downloads run at a time. The files arrive in the order of urls.

Compared with flatMapMerge

flatMapMerge emits each result when it is ready, in any order. mapAsync keeps the order, so one slow call holds back the results after it.

How it runs

  • mapAsync reads the next upstream value only when fewer than concurrency calls are waiting. So at most concurrency results are in memory.

  • A failure in transform or in the upstream cancels all running calls, and the flow fails with that exception.

Parameters

concurrency

the largest number of calls that run at the same time. At least 1.

Throws