How to flatten a List of Futures in Scala

2019-01-17 14:51发布

问题:

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!

回答1:

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.