Reputation: 1522
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
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
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:
map
converts Future("X")
to Future(("A", "X"))
.map
converts each ("A", Future("X"))
into an Future(("A", "X"))
, thus giving you a Seq[Future[(String, String)]]
. sequence
on that to obtain Future[Seq[(String, String)]]
Upvotes: 6