Ole*_*han 2 coroutine kotlin kotlinx.coroutines
我需要做平行平面图。假设我有以下代码:
val coll: List<Set<Int>> = ...
coll.flatMap{set -> setOf(set, set + 1)}
Run Code Online (Sandbox Code Playgroud)
我需要这样的东西:
coll.pFlatMap{set -> setOf(set, set + 1)} // parallel execution
Run Code Online (Sandbox Code Playgroud)
Kotlin不提供任何开箱即用的线程。但是您可以使用kotlinx.coroutines执行以下操作:
val coll: List<Set<Int>> = ...
val result = coll
.map {set ->
// Run each task in own coroutine,
// you can limit concurrency using custom coroutine dispatcher
async { doSomethingWithSet(set) }
}
.flatMap { deferred ->
// Await results and use flatMap
deferred.await() // You can handle errors here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
846 次 |
| 最近记录: |