I have some code that works for a simple case (2 Futures) but I can't quite find the way to generalize it for an unlimited number of Futures.
What I want to do is create some code that calls a future and, when that future is completed, call another one, and when this one is completed call another one, and so on.
I need the result of each call to be completed before calling the next one because I may not need to call it again (this is my stopping condition).
I know this can be solved explicitly with recursion, but I would like, if at all possible, a solution using for comprehensions and/or folds. I feel there must be a solution like that but I can't write it correctly.
Here's a a function that generates a a list of two random ints
def nextValue: Future[List[Int]] = Future{
Thread.sleep(1000)
val num1 = Random.nextInt(10)
val num2 = Random.nextInt(10)
List(num1,num2)
}
Now I would like to compose infinitely many such futures and join them all at the end (a single future of a list)
I'm just calling await.result for testing purposes
This works for 2 levels, but how to generalize it for N calls?
Await.result({
nextValue.flatMap{ value1 =>
nextValue.map{ value2 =>
value1 ++ value2
}
}
},1.minute)