Skip to content

Instantly share code, notes, and snippets.

@kellydavid
Created August 15, 2019 09:48
Show Gist options
  • Save kellydavid/1e389f214ea5f60c1e0917cb39bb2ebe to your computer and use it in GitHub Desktop.
Save kellydavid/1e389f214ea5f60c1e0917cb39bb2ebe to your computer and use it in GitHub Desktop.
zio retry update with ref
import zio._
import zio.clock._
//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 foo(number: Ref[Int]): IO[Int, String] =
for {
a <- number.get
_ <- UIO(println(s"foo=$a"))
res <- a match {
case 5 => ZIO.succeed("five")
case 2 => ZIO.succeed("two")
case _ => ZIO.fail(a - 1)
}
} yield res
def bar(number: Ref[Int]): ZIO[Clock, Int, String] =
foo(number)
.tapError(e => number.update(_ => e))
.retry(Schedule.recurs(5))
.orElse(ZIO.succeed("Couldn't find a match"))
val runtime = new DefaultRuntime {}
def run(number: Int): ZIO[Clock, Int, String] =
for {
num <- Ref.make(number)
barRes <- bar(num)
} yield barRes
def runHelper(number: Int): Unit = println(runtime.unsafeRun(run(number)))
runHelper(5)
runHelper(2)
runHelper(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment