Skip to content

Instantly share code, notes, and snippets.

@f0ster
Created June 28, 2019 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f0ster/a8c54986bfcf09778ae913545be0b280 to your computer and use it in GitHub Desktop.
Save f0ster/a8c54986bfcf09778ae913545be0b280 to your computer and use it in GitHub Desktop.
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