Reputation: 751
I have some functions which return Future
s. The callers register callbacks by onComplete
.
def makeHttpRequest(): Future[T] = ???
makeHttpRequest().onComplete {
case Success(v) => ???
case Failure(ex) => ???
}
Now I want to enable retries on these functions (or function callings). Is there any suggestion on how to achieve this?
Upvotes: 0
Views: 327
Reputation: 48420
There is no retry capability out-of-the-box. However based on Retry a function that returns a Future consider
def retry[T](n: Int, expr: => Future[T]): Future[T] =
Future.unit.flatMap(_ => expr).recoverWith {
case e if n > 1 => retry(n - 1, expr)
case e => Future.failed(e)
}
retry(3, makeHttpRequest())
https://scalafiddle.io/sf/otseSX0/0
or consider dedicated library such as softwaremill/retry.
Upvotes: 5
Reputation: 13985
def makeHttpRequest(maxRetryCount: Int, currentRetryCount: Int = 0): Future[T] = {
val responseFuture = ???
if (currentRetryCount == maxRetryCount)
responseFuture
else
responseFuture.recoverWith(makeHttpRequest(maxRetryCount, currentRetryCount + 1))
}
makeHttpRequest(3).onComplete {
case Success(v) => ???
case Failure(ex) => ???
}
Upvotes: 0