Skip to content

Instantly share code, notes, and snippets.

@LukaJCB
Created November 6, 2018 12:35
Show Gist options
  • Save LukaJCB/ed126614667cfc8f735880677bdc4876 to your computer and use it in GitHub Desktop.
Save LukaJCB/ed126614667cfc8f735880677bdc4876 to your computer and use it in GitHub Desktop.
Fiber Alternative distributivity
import cats._
import cats.effect._
import scala.concurrent.duration._
import cats.implicits._
import scala.language.higherKinds
implicit val ctx =
IO.contextShift(scala.concurrent.ExecutionContext.global)
implicit val timer =
IO.timer(scala.concurrent.ExecutionContext.global)
val a = IO(println("Hi!"))
val b = IO.sleep(1.second) *> IO(println("Whatup?"))
val c = IO.sleep(2.seconds) *> IO(println("Fine"))
def par[F[_], A](x: Fiber[F, A], y: Fiber[F, A])(implicit F: Concurrent[F]): Fiber[F, (A, A)] = {
type Fib[A] = Fiber[F, A]
Applicative[Fib].map2(x, y)((a, b) => (a, b))
}
def race[F[_], A](x: Fiber[F, A], y: Fiber[F, A])(implicit F: Concurrent[F]): Fiber[F, A] =
Fiber(
F.racePair(x.join, y.join).flatMap {
case Left((a, fib)) => F.as(fib.cancel, a)
case Right((fib, a)) => F.as(fib.cancel, a)
},
F.map2(x.cancel, y.cancel)((_, _) => ()))
val x = for {
fibA <- a.start
fibB <- b.start
fibC <- c.start
_ <- par(fibA, race(fibB, fibC)).join
} yield ()
val y = for {
fibA <- a.start
fibB <- b.start
fibC <- c.start
_ <- race(par(fibA, fibB), par(fibA, fibC)).join
} yield ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment