How to flatten a List of Futures in Scala

mljohns89 picture mljohns89 · Nov 3, 2014 · Viewed 21.6k times · Source

I want to take this val:

val f = List(Future(1), Future(2), Future(3))

Perform some operation on it (I was thinking flatten)

f.flatten

And get this result

scala> f.flatten = List(1,2,3)

If the flatten method isn't appropriate here, that's fine. As long as I get to the result.

Thanks!

Answer

Gabriele Petronella picture Gabriele Petronella · Nov 3, 2014

Future.sequence takes a List[Future[T]] and returns a Future[List[T]].

You can do

Future.sequence(f) 

and then use map or onComplete on it to access the list of values.