score:0

This is an example of retry function based on Future.recoverWith If you run it you can see that it prints "run process" until the Future is successful but not more than 'times' times

object X extends App{
  type Request = String
  type Response = String
  import scala.concurrent.ExecutionContext.Implicits.global
  def retry(request: Request, process: Request => Future[Response], times: Int): Future[Response] ={
    val responseF = process(request)
    if(times > 0)
      responseF.recoverWith{
        case ex => println("fail")
          retry(request, process, times - 1)
      }
    else
      responseF
  }

  def process(s: Request): Future[Response] = {
    println("run process")
    if(Random.nextBoolean()) Future.successful("good") else Future.failed(new Exception)
  }

  val result = retry("", process, 3)
  import scala.concurrent.duration._
  println(Await.result(result, 1.second))

}

Related Query

More Query from same tag