Created
June 28, 2019 22:21
-
-
Save f0ster/a8c54986bfcf09778ae913545be0b280 to your computer and use it in GitHub Desktop.
Recursive Retryables in scala
This file contains 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
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