I think what you are looking for is Future.sequence method that allows you reduce a sequence of Future
s into a single Future
. Here is a simple example:
def createFuture(name: String, sleep: Int): Future[(String, Int)] = {
Future({
println(s"Starting $name with sleep $sleep")
Thread.sleep(sleep)
println(s"After $name")
(name, sleep)
})
}
val rnd = new Random()
val fa = createFuture("A", rnd.nextInt(1000) + 500)
val fb = createFuture("B", rnd.nextInt(1000) + 500)
val ff = Future.sequence(List(fa, fb)).flatMap(l => createFuture("C" + l.map(_._2).sum, 100))
Await.result(ff, Duration.Inf)
Output for one of runs is:
Starting B with sleep 1287
Starting A with sleep 550
After A
After B
Starting C1837 with sleep 100
After C1837
If you also want to have "fast failure", you may consider a more complicated answers from How to wait for several Futures