object Example:
var counter: Int = 3
val tendToFail: zio.ZIO[Any, Throwable, Int] =
.ZIO.attempt {
zioif (counter > 0) then
println(s"Failing with counter = ${counter}")
= counter - 1
counter throw new Exception("nope")
else 42
}
val keepTry: zio.ZIO[Any, Throwable, Unit] =
import zio.durationInt
tendToFail.retry(
.Schedule.exponential(1.second)
zio&& zio.Schedule.recurs(5)
)
.map(result => println(result))
object Main extends zio.ZIOAppDefault:
override def run: zio.ZIO[Any, Throwable, Unit] =
.keepTry Example
This file is literate Scala, and can be run using Codedown:
$ curl https://earldouglas.com/posts/scala/zio/backoff.md |
codedown scala > script.scala |
scala-cli -q --scala 3.1.3 --dep dev.zio::zio:2.0.0 _.scala
Failing with counter = 3
Failing with counter = 2
Failing with counter = 1
42