Search code examples
scaladictionaryfuturefor-comprehension

Scala, execute map of futures


What is the best way to go from

Map[String, Future[A]]

to

Map[String, A]

where A is the result of the corresponding future's execution?

This won't compile:

val results = for {
  (key, future) <- myMap
  result <- future
} yield (key, result)

as I can't mix futures and iterables in the same for comprehension.


Solution

  • If you convert it into a Seq[Future[(String,A)]], you can then use Future.fold to get it back a single Future[Map[...]]:

    def transform[A](m: Map[String, Future[A]]): Future[Map[String, A]] = {
      val seq: Seq[Future[(String, A)]] = m.toSeq.map { case (key, f) =>
        f.map(i => key -> i)
      }
    
      Future.fold(seq)(Map.empty[String, A])(_ + _)
    }
    

    Then redeem the single future as normal.