Last active
December 13, 2015 19:39
-
-
Save rrodseth/4964397 to your computer and use it in GitHub Desktop.
Composing Futures with a for-comprehension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Credit: http://blog.knoldus.com/2013/01/27/akka-futures-using-for-comprehensions/ | |
import akka.actor.ActorSystem | |
import scala.concurrent.{future, Future, Await } | |
import scala.concurrent.ExecutionContext.Implicits.global | |
object FutureComposingWithFor extends App { | |
def longRunningFunction(number: Int) = { | |
// Sleep for 3 seconds and return number | |
Thread.sleep(3000) | |
number | |
} | |
val system = ActorSystem("future") | |
val startTime = System.currentTimeMillis | |
val future1 = future { longRunningFunction(1) } | |
val future2 = future { longRunningFunction(2) } | |
val future3 = future { longRunningFunction(3) } | |
val futuresum = for { | |
a <- future1 | |
b <- future2 | |
c <- future3 | |
} yield (a + b + c) | |
futuresum onSuccess { | |
case sum => | |
val elapsedTime = ((System.currentTimeMillis - startTime) / 1000.0) | |
println("Sum of 1, 2, and 3 is " + sum + " calculated in " + elapsedTime + " seconds") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment