How to combine Futures of different types into a single Future without using zip()

Peter Lerche picture Peter Lerche · Jun 22, 2012 · Viewed 8k times · Source

I want to create a Future of type Future[(Class1,Class2,Class3)] from below code. However the only way I have found to do this is by using zip(). I find the solution ugly and properly not optimal. Can anybody enlightened me.

val v = for (
    a <- {
        val f0:Future[Class1] = process1
        val f1:Future[Class2] = process2
        val f2:Future[Class3] = process3
        f0.zip(f1).zip(f2).map(x => (x._1._1,x._1._2,x._2))
    } yield a  // Future[(Class1,Class2,Class3)]

I have also tried to use Future.sequence(List(f0, f1, f2)) but this will not work as the new Future will have type of Future[List[U]] where U is the lub of Class1/2/3 whereas I want a 3-tuple preserving the original types

Answer

Viktor Klang picture Viktor Klang · Jun 22, 2012
val result: Future[(Class1, Class2, Class3)] = {
  val f1 = process1
  val f2 = process2
  val f3 = process3
  for { v1 <- f1; v2 <- f2; v3 <- f3 } yield (v1, v2, v3)
}