BusyBee
BusyBee

Reputation: 95

Call a method that returns future n times

I want to call a method n times. Every subsequent call should be made only if the previous call was a success. This method returns a future. The code I attempted looks like this

    def doSomething: Future[R] = Future {
              //some logic 
              ???
    }

    def outer() = {
      val range = { 1 to 5 }

      def inner(range: Seq[Int]): Future[R]= 
        range.headOption match {
          case Some(head) =>
            doSomething.flatMap { _ => inner(range.tail)} 
          case None => ???
        }
      inner(range)
    }

In case None, I want to return the value of the last future that ran. How do achieve this?

Upvotes: 1

Views: 73

Answers (1)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

Something like this?

// assumes that implicit ExecutionContext is available
// if it isn't available here add it to signature
def callMeNTimes[T](n: Int)(future: => Future[T]): Future[T] =
  if (n <= 0) Future.failed(new Exception("Cannot run future less that 1 times"))
  else if (n == 1) future
  else future.flatMap(_ => callMeNTimes(n-1)(future))

callMeNTimes(5)(doSomething)

If you need to aggregate results across runs you could do something like:

def repeat[A](n: Int, init: A)(future: A => Future[A]): Future[A] =
  if (n <= 0) Future.successful(init)
  else future(init).flatMap(a => repeat(n-1, a)(future))

Upvotes: 3

Related Questions