rrva
08/19/2022, 10:07 AMfun <A, B> Iterable<A>.parallelMap(context: CoroutineContext, f: suspend (A) -> B): List<B> = runBlocking {
map { async(context) { f(it) } }.map { it.await() }
}
@OptIn(ExperimentalCoroutinesApi::class)
private val apiPool = Dispatchers.IO.limitedParallelism(10)
val results = foo.parallelMap(apiPool) { fetchStuffFromRestAPI(it.id) }
Sam
08/19/2022, 10:10 AMparallelMap
function to a suspend
function:
suspend fun <A, B> Iterable<A>.parallelMap(f: suspend (A) -> B): List<B> = coroutineScope {
map { async { f(it) } }.map { it.await() }
}
.map { it.await() }
for .awaitAll()
which will fail fast if one of the child jobs fails — depends on your approach to the structured concurrencyrrva
08/19/2022, 11:04 AMSam
08/19/2022, 12:40 PM