Skip to content

Instantly share code, notes, and snippets.

@kellydavid
Created August 14, 2019 22:39
Show Gist options
  • Save kellydavid/1e479a1895f2b7782c40f6700a0fc3af to your computer and use it in GitHub Desktop.
Save kellydavid/1e479a1895f2b7782c40f6700a0fc3af to your computer and use it in GitHub Desktop.
trying out zio retry mechanism
package ziowork
import zio._
import zio.clock.Clock
import zio.clock._
import zio.duration._
import zio.random.Random
object MyApp extends scala.App {
case class Resulting(success: Option[String], failure: Option[Int])
def foo1(a: Int): UIO[Resulting] =
for {
_ <- UIO(println("foo a=" + a))
res <- a match {
case 5 => UIO(Resulting(Some("five"), None))
case other => UIO(Resulting(None, Some(other)))
}
} yield res
def bar1(b: Int): UIO[Resulting] =
for {
_ <- UIO(println("bar b=" + b))
res <- b match {
case 2 => UIO(Resulting(Some("two"), None))
case other => UIO(Resulting(None, Some(other)))
}
} yield res
//
// def foobar(a: Int): IO[Int, String] =
// for {
// _ <- UIO(println("stuff"))
// performOp <- foo(a)
// answer <- performOp match {
// case Resulting(Some(str), None) => ZIO.succeed(str)
// case Resulting(None, Some(integer)) => ZIO.fail(integer)
// case _ => ZIO.fail(-1)
// }
// } yield answer
def resultingToEither(resulting: Resulting): Either[Int, String] =
resulting match {
case Resulting(Some(success), None) => Right(success)
case Resulting(None, Some(failure)) => Left(failure)
case Resulting(_, _) => Left(-1)
}
def foo(number: Int): IO[Int, String] =
for {
_ <- UIO(println(s"foo=$number"))
res <- number match {
case 5 => ZIO.succeed("five")
case 2 => ZIO.succeed("two")
case _ => ZIO.fail(number - 1)
}
} yield res
def bar(number: Int): ZIO[Clock, Int, String] =
foo(number)
.retry(Schedule.recurs(5))
.orElse(ZIO.succeed("Couldn't find a match"))
def foobar(a: Int): ZIO[Any with Random with Clock, Int, String] = //ZIO[Any with Clock, Int, String] =
for {
_ <- UIO(println("stuff"))
answer <- foo(a)
.retry(Schedule.recurs(5))
.orElse(UIO("I give up"))
// .retry(Schedule.recurs(3) && Schedule.exponential(300.milliseconds).jittered)
// .orElse(bar(a).map(resultingToEither).absolve)
// .retry(Schedule.recurs(3) && Schedule.exponential(300.milliseconds).jittered)
// .retryOrElse(Schedule.recurs(3), (e: Int, s: Int) => {println("s="+s); bar(e).map(resultingToEither).absolve})
// .orElse(UIO("four"))
} yield answer
val runtime = new DefaultRuntime {}
def fooBarHelper(a: Int): Unit/*Either[Int, String]*/ = println(runtime.unsafeRun(MyApp.foobar(a).either))
fooBarHelper(5)
println
fooBarHelper(2)
println
fooBarHelper(4)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment