Reputation:
Is there a method (or simple way) in scala that helps to transform List[Future[...]]
to List[...]
?
If such a method is in the Seq, then it is also suitable. I spent a lot of time looking, but I couldn't find anything. Thanks
Upvotes: 0
Views: 298
Reputation: 48400
sequence
can turn List[Future[A]]
to Future[List[A]]
and then you could await the future
val fxs: Future[List[Int]] = Future.sequence(List(Future(1), Future(2)))
val xs: List[Int] = Await.result(fxs, Duration.Inf)
// work with xs
however usually it is preferable to map over the future instead of awaiting like so
fxs.map { xs: List[Int] =>
// work with xs
}
Upvotes: 2
Reputation: 26579
You want Future.sequence and then you get a Future[List[A]] which you can then decide how you want to handle.
Upvotes: 5