Last active
May 25, 2024 10:19
-
-
Save dacr/3f3e68cb4f50a7f5787cca305af22208 to your computer and use it in GitHub Desktop.
ZIO learning - retrying is possible, very easy and loggable / published by https://github.com/dacr/code-examples-manager #6e276a62-10bb-4563-a5a9-fcb368d3a7e9/eea1d48cad152ce319a6251726d0047232369b15
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : ZIO learning - retrying is possible, very easy and loggable | |
// keywords : scala, zio, learning, pure-functional, schedule, decision, exponentialBackOff, jitter, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 6e276a62-10bb-4563-a5a9-fcb368d3a7e9 | |
// created-on : 2021-04-02T15:36:11+02:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "dev.zio::zio:2.0.13" | |
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0" | |
// --------------------- | |
import zio.*, zio.worksheet.* | |
import zio.Schedule.Decision | |
val logic = for { | |
content <- ZIO.attempt(scala.io.Source.fromURL("https://mapland.fr/ip")) // just for the example | |
//content <- ZIO.attempt(scala.io.Source.fromURL("https://mapland.frxx/ip")) // just for the example | |
} yield content.getLines().mkString("\n") // just for the example | |
val schedule1 = Schedule.spaced(1.second) && Schedule.recurs(5) | |
val schedule2 = (Schedule.exponential(1.second) && Schedule.recurs(3)).onDecision((state, out, decision) => | |
decision match { | |
case Decision.Done => ZIO.logInfo("No more retry attempt !") | |
case Decision.Continue(interval) => ZIO.logInfo(s"Will retry at ${interval.start}") | |
} | |
) | |
val schedule3 = // exponentialBackOffWithJitter | |
Schedule.exponential(100.millis, 2).jittered && Schedule.recurs(4) | |
// ------------------------------------------------------------- | |
val logicWithAutoRetries = logic.retry(schedule2) | |
// ------------------------------------------------------------- | |
val result = logicWithAutoRetries.unsafeRun | |
println(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment