Skip to content

Instantly share code, notes, and snippets.

@Daenyth
Last active December 11, 2022 21:31
Show Gist options
  • Save Daenyth/d78a37254210f1105b3e95bffa8cd5fa to your computer and use it in GitHub Desktop.
Save Daenyth/d78a37254210f1105b3e95bffa8cd5fa to your computer and use it in GitHub Desktop.
fs2 Stream 1.x / Simple example of retry with logging
import cats.effect.Sync
import io.chrisdavenport.log4cats.Logger
import cats._
import cats.implicits._
import scala.concurrent.duration._
class RetryExample[F[_]](implicit F: Sync[F], log: Logger[F]) {
case class ApiError(msg: String) extends Exception(msg)
private def getTempFromInternet: EitherT[F, ApiError, Float] = ???
def getTempWithRetries: F[Float] = {
val get: F[Float] = getTempFromInternet.value.map(_.leftWiden[Throwable]).rethrow
val maxAttempts = 5
fs2.Stream.retry(
fo = get.onError(e => log.error(e)("Attempt failed")),
delay = 500.millis,
nextDelay = _ * 2,
maxAttempts = maxAttempts,
).onError(e => log.error(e)(s"Failed to get temperature after $maxAttempts tries"))
.compile.lastOrError
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment