2

If I have a List<A> and a function suspend (A) -> B, how can I apply this function on the list in parallel?

1
  • What do you mean by in parallel? Commented Aug 2, 2020 at 15:35

2 Answers 2

7
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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.