Search code examples
kotlincoroutinekotlinx.coroutines

How to do parallel flatMap in Kotlin?


I need to do parallel flat map. Let's say I have this code:

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

I need something like this:

coll.pFlatMap{set -> setOf(set, set + 1)} // parallel execution

Solution

  • Kotlin doesn’t provide any threading out of the box. But you can use kotlinx.coroutines to do something like this:

    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
     }