Skip to content

Instantly share code, notes, and snippets.

@kolov
Created May 31, 2018 22:55
Show Gist options
  • Save kolov/1ad70efde3a8fb8f2d02c38ede877ac7 to your computer and use it in GitHub Desktop.
Save kolov/1ad70efde3a8fb8f2d02c38ede877ac7 to your computer and use it in GitHub Desktop.
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import cats.effect.{IO, Timer}
import cats._
import cats.implicits._
object X extends App {
def recoverTimeout[A](fa: IO[A], after: FiniteDuration, fallback: A)
(implicit timer: Timer[IO]): IO[A] = {
IO.race(fa.recover { case _ => fallback}, timer.sleep(after)).flatMap {
case Left(a) => IO.pure(a)
case Right(_) => IO.pure(fallback)
}
}
def call1 = { println("starting call1"); Thread.sleep(1000);println("finished call1"); 1}
def call2 = { println("starting call2"); Thread.sleep(2000);println("finished call2"); 2}
def call3 = { throw new Exception("boom")}
println("Starting")
private val duration: FiniteDuration = 1.5 second // try 0.5, 2.5
val l = (
recoverTimeout(IO.shift *> IO { call1 }, duration, 11),
recoverTimeout(IO.shift *> IO { call2 }, duration, 12),
recoverTimeout(IO.shift *> IO { call3 }, duration, 13)
).parMapN( (x,y,z) => (x,y,z))
val result = l.unsafeRunSync()
println(s"Finished $result")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment