Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing N times a Scala Future

I am trying to find a more elegant way to execute 2 times a function which returns a Future[HttpReponse] and then to use the response of the 2-end call.

for {
    // function post returns a Future[HttpResponse]
    response <- post(uri, payload) // 1st
    response <- post(uri, payload) // 2end
} yield {
    // do something with the 2end response
}

This does not work:

for {
    2 times response <- post(uri, payload)
} yield {
    // response becomes of type Any instead of HttpResponse
}
like image 680
Martin Avatar asked Mar 01 '26 07:03

Martin


1 Answers

If you need to make two sequential calls to a method that returns Future, you can use flatMap.

post(uri, payload).flatMap(_ => post(uri, payload))

This will not start the second post operation until the first one completes.

If you have multiple chained calls you can use foldLeft on a Range to apply this the appropriate number of times:

(0 to N-1).foldLeft(post(uri, payload)){
  case (prev, _) => prev.flatMap(_ => post(uri, payload))
}

In practice you would probably use the value from the Range to track progress on this operation rather than discarding it.

like image 69
Tim Avatar answered Mar 03 '26 21:03

Tim