joesan
joesan

Reputation: 15345

Scala transforming a Seq with Future

I have a Seq of a tuple that looks like this:

Seq[(Future[Iterable[Type1]], Future[Iterator[Type2]])]

I want to transform this into the following:

Future[Seq([Iterable[Type1], [Iterable[Type2])]

Is this even possible?

Upvotes: 2

Views: 781

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

A bit simpler than Till Rohrmann's answer. Not tested, but should work.

val seq: Seq[(Future[Iterable[Type1]], Future[Iterable[Type2]])] = ...

val seq2 = Future.traverse(seq) { case (f1, f2) => f1.zip(f2) } 

Or

val seq1 = seq.map { case (f1, f2) => f1.zip(f2) } 
// Seq[Future[(Iterable[Type1], Iterable[Type2])]]

val seq2 = Future.sequence(seq1)
// Future[Seq([Iterable[Type1], [Iterable[Type2])]

If you actually have Iterator[Type2], as in the question, use f2.map(_.toIterable) instead of just f2.

Upvotes: 4

Till Rohrmann
Till Rohrmann

Reputation: 13346

This should do the trick

val a: Seq[(Future[Iterable[Type1]], Future[Iterable[Type2]])] = ...

val b: Future[Seq[(Iterable[Type1], Iterable[Type2])]] = Future.sequence(a.map{
  case (l, r) => l.flatMap(vl => r.map(vr => (vl, vr)))
})

Upvotes: 5

Related Questions