ps0604
ps0604

Reputation: 1071

Returning two Scala futures when both end

The method1 below is an attempt to return the results of two Future methods someFutureMethod1 and someFutureMethod2 combined. Any ideas how to make this work? Ideally the method that ends first should wait until the second ends, and then return the future values combined.

  def method1 ( s: Seq[Int]): Future [(Int,Int)] = {
      s.map { sx =>
          val future = someFutureMethod1 (sx)
          future.map {
            result => result
          }
          val future2 = someFutureMethod2 (sx)
          future2.map {
            result2 => result2
          }
          (result,result2)  // <-- the method should return the two results in the future
       }
  }


def someFutureMethod1 (i: Int) = Future { 
    i + 1
  }

def someFutureMethod2 (i: Int) = Future { 
    i + 2
  }

Upvotes: 0

Views: 170

Answers (1)

zhelezoglo
zhelezoglo

Reputation: 212

You combine Future's in a map, so it looks like you have to return a Seq of such Future's:

def method1 ( s: Seq[Int]): Seq[Future [(Int,Int)]] =
  s.map { sx =>
    val future = someFutureMethod1 (sx)
    val future2 = someFutureMethod2 (sx)
    future.zip(future2)
  }

Upvotes: 1

Related Questions