Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 444
mljohns89 Avatar asked Nov 03 '14 15:11

mljohns89


People also ask

How does Scala Futures work?

Future represents a result of an asynchronous computation that may or may not be available yet. When we create a new Future, Scala spawns a new thread and executes its code. Once the execution is finished, the result of the computation (value or exception) will be assigned to the Future.

What is future sequence?

sequence takes a list of futures and transforms it into a single future of list in an asynchronous manner. For instance, assume that you have a list of independent jobs to be run simultaneously. In such a case, the list of futures can be composed into a single future of list using Future. sequence.


1 Answers

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.

like image 70
Gabriele Petronella Avatar answered Sep 24 '22 17:09

Gabriele Petronella