简体   繁体   中英

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)]] ?

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)]]

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM