I have a scenario wherein I get a List of String messages and I have to iterate through the String and call another method which is sort of a long running process. I have to then collect the results of this long running process and concatenate the results and send it back to the user interface. I'm pretty new to these Future concepts in Scala. I'm using Play framework where-in the list of Strings will come from the user interface. Here is how my first attempt at implementing ht scenario looks:
def futuresTest(strList: List[String]) = Action {
Async {
val ftrList: List[Future[String]] =
strList.map(s => Akka.future {longRunningCall(s)} ).toList
val futureResultList = Future.sequence(ftrList)
val jsonResponse: String =
futureResultList.map(_.sum).asInstanceOf[String]
Akka.future { Ok(jsonResponse) }
}
}
For simplicity, the longRunningCall would just return a String. Later I will tie it up to the original implementation.
def longRunningCall(s: String) = "test"
My question here is that in the statement:
val ftrList: List[Future[String]] =
strList.map(s => Akka.future {longRunningCall(s)} ).toList
I would assume that the ftrList will be populated asynchronously and when it hits the following line, I'm guaranteed that the futureResultList would contain all the elements (i.e., strList and futureResultList size would be equal?
val futureResultList = Future.sequence(ftrList)
Please advice!