Tanvir
Tanvir

Reputation: 1522

Scala - Future.sequence on Tuples

I have a Seq of Tuples:

val seqTuple: Seq[(String, Future[String])] = Seq(("A", Future("X")), ("B", Future("Y")))

and I want to get:

val futureSeqTuple: Future[Seq[(String, String)]] = Future(Seq(("A", "X"), ("B", "Y")))

I know I can do:

val futureSeq: Future[Seq[String]] = Future.sequence(seqTuple.map(_._2))

but I am losing the first String in the Tuple.

What is the best way to get a Future[Seq[(String, String)]]?

Upvotes: 6

Views: 2349

Answers (2)

zkerriga
zkerriga

Reputation: 101

The answer given here works fine, but I think Future.traverse would work more succinctly here:

Future.traverse(seqTuple) {
  case (s1, s2Future) => s2Future.map{ s2 => (s1, s2) }
}

This function involves converting the input argument :)

Upvotes: 5

Andrey Tyukin
Andrey Tyukin

Reputation: 44908

Use the futures in tuples to map each tuple to future of tuple first, then sequence:

Future.sequence(
  seqTuple.map{case (s1, fut_s2) => fut_s2.map{s2 => (s1, s2)} }
)

Step by step, from inner terms to outer terms:

  1. The inner map converts Future("X") to Future(("A", "X")).
  2. The outer map converts each ("A", Future("X")) into an Future(("A", "X")), thus giving you a Seq[Future[(String, String)]].
  3. Now you can use sequence on that to obtain Future[Seq[(String, String)]]

Upvotes: 6

Related Questions