arrow-fx / arrow.fx.typeclasses / Concurrent / racePair

racePair

abstract fun <A, B> CoroutineContext.racePair(fa: Kind<F, A>, fb: Kind<F, B>): Kind<F, RacePair<F, A, B>>

Race two tasks concurrently within a new F. Race results in a winner and the other, yet to finish task running in a Fiber.

import arrow.Kind
import arrow.fx.*
import arrow.fx.extensions.io.concurrent.concurrent
import arrow.fx.typeclasses.*
import kotlinx.coroutines.Dispatchers

fun main(args: Array<String>) {
  fun <F> Concurrent<F>.example(): Kind<F, String> =
    //sampleStart
    fx.concurrent {
      val racePair = !Dispatchers.Default.racePair(never<Int>(), just("Hello World!"))
      racePair.fold(
        { _, _ -> "never cannot win race" },
        { _, winner -> winner }
      )
  }
  //sampleEnd

  val r = IO.concurrent().example().fix().unsafeRunSync()
  println("Race winner result is: $r")
}

Parameters

this - @racePair CoroutineContext to execute the source F on.

fa - task to participate in the race

fb - task to participate in the race

Return F either Left with product of the winner’s result fa and still running task fb, or Right with product of running task fa and the winner’s result fb.

See Also

raceN

Do you like Arrow?

Arrow Org
<