mcpiroman
03/02/2022, 10:14 AMsuspend fun processAll(items: List<Item>) = coroutineScope {
val channel = Channel<Item>(Channel.UNLIMITED)
items.forEach { channel.trySendBlocking(it).getOrThrow() }
repeat(4) {
launch {
for (item in channel) // process
}
}
}
Bonus point - is there a facility to automatically pick an optimal level of parallelism, instead of, in this example, hardcoded 4?Sam
03/02/2022, 10:18 AMitems.chunked(...)
to split the list into parts, and launch a separate coroutine for each chunk.suspend fun processAll(items: List<Item>) = coroutineScope {
items.map { async { process(item) } }.awaitAll()
}
mcpiroman
03/02/2022, 10:22 AMchuncked
thing is that each item can take different time to process, so near the end the level of parallelism will decrease