Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Recursive Retryables in scala
import scala.concurrent.{ExecutionContext, Future}
trait Retryable {
// Returning T, throwing the exception on failure
@annotation.tailrec
final def retryDangerously[T](n: Int)(fn: => T): T = {
util.Try { fn } match {
case util.Success(x) => x
case _ if n > 1 => retryDangerously(n - 1)(fn)
case util.Failure(e) => throw e
}
}
// Returning a Try[T] wrapper
@annotation.tailrec
final def retry[T](n: Int)(fn: => T): util.Try[T] = {
util.Try { fn } match {
case util.Failure(_) if n > 1 => retry(n - 1)(fn)
case fn => fn
}
}
// Returning Future[T]
def retryFuture[T](times: Int)(f: => Future[T])(implicit executor: ExecutionContext): Future[T] =
f recoverWith { case _ if times > 0 => retryFuture(times - 1)(f) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment