Scala transform Map [Int, Future [Seq [T]]] to Future [Map [Int, Seq [T]]]

How can i convert

Map[Int, Future[Seq[T]]]

      

to

Future[Map[Int, Seq[T]]]

      

in Scala without waiting for the future.

Example:

Map( 
  1 -> Future.successful(Seq(100, 200, 300)),
  2 -> Future.successful(Seq(500, 600, 700))
)

      

+3


source to share


1 answer


This should do it:

val m = Map( 
  1 -> Future.successful(Seq(100, 200, 300)),
  2 -> Future.successful(Seq(500, 600, 700))
)

Future.sequence { m.map { case (i, f) => f.map((i, _))} }.map(_.toMap)

      

Working from the inside, I displayed the key values ​​from (Int, Future[T])

to Future[(Int, T)]

, then was able to use s Future.sequence

in the resulting sequence Future

. This collapsed Future

can then be mapped back to Map

.



This can be made a little shorter by using Future.traverse

as suggested by @ IonutG.Stan:

Future.traverse(m){ case (i, f) => f.map((i, _))}.map(_.toMap)

      

This will create a new collection in Future

from m

, using the same function that was provided earlier to map tuples to future tuple futures.

+7


source







All Articles