Kotlin:“并行”在列表上应用挂起函数?

Gop*_*ala 2 parallel-processing concurrency suspend kotlin kotlin-coroutines

如果我有 aList<A>和 a 函数suspend (A) -> B,我如何在列表上并行应用这个函数?

luk*_*kle 7

coroutineScope {
    list.map {
        async {
            process(it)
        }
    } // List<Deferred<B>>
    .awaitAll() // List<B>
}

suspend fun process(a: A): B {
   ...
}
Run Code Online (Sandbox Code Playgroud)

这假设您已经处于suspend上下文中。否则,您需要在适当的作用域上启动新的协程,而不是使用coroutineScope作用域函数。