简体   繁体   中英

How to flatten a List of Futures in Scala

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM