user6502167
user6502167

Reputation: 751

Enable retries on the Scala function returning a Future

I have some functions which return Futures. 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

Answers (2)

Mario Galic
Mario Galic

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

sarveshseri
sarveshseri

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

Related Questions