Scala Language Combine Multiple Futures – For Comprehension


Example

The for comprehension is a compact way to run a block of code that depends on the successful result of multiple futures.

With f1, f2, f3 three Future[String]'s that will contain the strings one, two, three respectively,

val fCombined = 
    for {
        s1 <- f1
        s2 <- f2
        s3 <- f3
    } yield (s"$s1 - $s2 - $s3")

fCombined will be a Future[String] containing the string one - two - three once all the futures have completed successfully.

Note that an implicit ExectionContext is assumed here.

Also, keep in mind that for comprehension is just a syntactic sugar for a flatMap method, so Future objects construction inside for body would eliminate concurrent execution of code-blocks enclosed by futures and lead to sequential code. You see it on example:

val result1 = for {
  first <- Future {
    Thread.sleep(2000)
    System.currentTimeMillis()
  }
  second <- Future {
    Thread.sleep(1000)
    System.currentTimeMillis()
  }
} yield first - second

val fut1 = Future {
  Thread.sleep(2000)
  System.currentTimeMillis()
}
val fut2 = Future {
  Thread.sleep(1000)
  System.currentTimeMillis()
}
val result2 = for {
  first <- fut1
  second <- fut2
} yield first - second

Value enclosed by result1 object would be always negative while result2 would be positive.

For more details about the for comprehension and yield in general, see http://docs.scala-lang.org/tutorials/FAQ/yield.html