//arrow-fx-coroutines/arrow.fx.coroutines/parTraverseEither

parTraverseEither

common suspend fun <A, B, E> Iterable<A>.parTraverseEither(f: suspend .([A](par-traverse-either.html)) -> <[E](par-traverse-either.html), [B](par-traverse-either.html)>): <[E](par-traverse-either.html), [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[B](par-traverse-either.html)>>

Traverses this Iterable and runs all mappers f on Dispatchers.Default. If one of the f returns Either.Left, then it will short-circuit the operation and cancelling all this running f, and returning the first encountered Either.Left.

Cancelling this operation cancels all running tasks.

common suspend fun <A, B, E> Iterable<A>.parTraverseEither(ctx: CoroutineContext = EmptyCoroutineContext, f: suspend .([A](par-traverse-either.html)) -> <[E](par-traverse-either.html), [B](par-traverse-either.html)>): <[E](par-traverse-either.html), [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[B](par-traverse-either.html)>>

Traverses this Iterable and runs all mappers f on CoroutineContext. If one of the f returns Either.Left, then it will short-circuit the operation and cancelling all this running f, and returning the first encountered Either.Left.

Coroutine context is inherited from a CoroutineScope, additional context elements can be specified with ctx argument. If the combined context does not have any dispatcher nor any other ContinuationInterceptor, then Dispatchers.Default is used. WARNING If the combined context has a single threaded ContinuationInterceptor, this function will not run in parallel.

Cancelling this operation cancels all running tasks.

import arrow.core.*
import arrow.fx.coroutines.*
import kotlinx.coroutines.Dispatchers

object Error
data class User(val id: Int, val createdOn: String)

suspend fun main(): Unit {
  //sampleStart
  suspend fun getUserById(id: Int): Either<Error, User> =
    if(id == 4) Error.left()
    else User(id, Thread.currentThread().name).right()

  val res = listOf(1, 2, 3)
    .parTraverseEither(Dispatchers.IO) { getUserById(it) }

  val res2 = listOf(1, 4, 2, 3)
    .parTraverseEither(Dispatchers.IO) { getUserById(it) }
 //sampleEnd
 println(res)
 println(res2)
}

Do you like Arrow?

Arrow Org
<