user13033677
user13033677

Reputation:

Transform from List[Future[...] to List[...] in Scala

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

Answers (2)

Mario Galic
Mario Galic

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

Viktor Klang
Viktor Klang

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

Related Questions