If I have a List<A> and a function suspend (A) -> B, how can I apply this function on the list in parallel?
2 Answers
coroutineScope { list.map { async { process(it) } } // List<Deferred<B>> .awaitAll() // List<B> } suspend fun process(a: A): B { ... } This assumes you are already in a suspend context. Otherwise, you need to launch a new coroutine on the appropriate scope instead of using the coroutineScope scoping function.
Comments
You can create an extension function on CoroutineScope, go through each element of the list and launch a coroutine for each element. In this way elements of the list will be processed in parallel. Some code snippet:
fun CoroutineScope.processListInParallel(list: List<A>): List<Deferred<B>> = list.map { async { // launch a coroutine processA(it) } } GlobalScope.launch { val list = listOf(A("name1"), A("name2"), A("name3")) val deferredList = processListInParallel(list) val results: List<B> = deferredList.awaitAll() // wait for all items to be processed } suspend fun processA(a: A): B { delay(1000) // emulate suspension return B("Result ${a.name}") } data class A(val name: String) {} data class B(val name: String) {} Note: GlobalScope is used here as an example, using it is highly discouraged, application code usually should use an application-defined CoroutineScope.
in parallel?