如何在Kotlin中进行并行flatMap?

问题描述 投票:2回答:1

我需要做平行平面地图。假设我有这段代码:

val coll: List<Set<Int>> = ...
coll.flatMap{set -> setOf(set, set + 1)}

我需要这样的东西:

coll.pFlatMap{set -> setOf(set, set + 1)} // parallel execution
kotlin coroutine kotlinx.coroutines
1个回答
4
投票

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
 }
© www.soinside.com 2019 - 2024. All rights reserved.