Skip to content

Instantly share code, notes, and snippets.

@noelmarkham
Last active August 29, 2015 14:01
Show Gist options
  • Save noelmarkham/4e8e5b4c705793ee93c0 to your computer and use it in GitHub Desktop.
Save noelmarkham/4e8e5b4c705793ee93c0 to your computer and use it in GitHub Desktop.
Spot the difference
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
def fut(name: String, waitTime: Duration, result: Int): Future[Int] = {
Future {
println(s"$name started")
Thread.sleep(waitTime.toMillis)
println(s"$name finished")
result
}
}
val f1 = for {
a <- fut("a", 500.milliseconds, 123)
b <- fut("b", 200.milliseconds, 321)
} yield a + b
val res1 = Await.result(f1, 1.second)
//-------
val cFut = fut("c", 500.milliseconds, 234)
val dFut = fut("d", 200.milliseconds, 432)
val f2 = for {
c <- cFut
d <- dFut
} yield c + d
val res2 = Await.result(f2, 1.second)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment