Last active
December 13, 2015 22:19
-
-
Save sudowork/4984088 to your computer and use it in GitHub Desktop.
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
| import scala.concurrent.{future, Await} | |
| import scala.concurrent.duration._ | |
| import scala.util.{Success, Failure} | |
| import scala.concurrent.ExecutionContext.Implicits.global | |
| import scala.language.postfixOps | |
| object TestFutures { | |
| def testAsyncWork { | |
| val f = future { | |
| Thread.sleep(1000) // simulating work | |
| 42 | |
| } | |
| f onComplete { println _ } | |
| println("I'm looking for the answer...") // This gets completed first! | |
| Await.ready(f, 5 seconds) // We block just so our test cases don't run into each other | |
| // blocking is normally bad! | |
| } | |
| // define some functions that perform "computations" | |
| val f1 = () => future { Thread.sleep(500); println("f1 calculated"); 20 } | |
| val f2 = () => future { Thread.sleep(500); println("f2 calculated"); 2 } | |
| val f3 = () => future { Thread.sleep(500); println("f3 calculated"); 2 } | |
| def testAsyncChaining { | |
| // this is not how we typically write it (see testAsyncChainingForComp for a better idea) | |
| val calc = f1().flatMap { a => | |
| f2().flatMap { b => | |
| f3().map { c => | |
| a * b + c | |
| } | |
| } | |
| } | |
| calc onComplete println | |
| Await.ready(calc, 5 seconds) | |
| } | |
| def testAsyncChainingForComp { | |
| val calc = for { | |
| a <- f1() | |
| b <- f2() | |
| if b > 9000 // Intermittent failure point | |
| c <- f3() | |
| } yield (a * b + c) | |
| calc onComplete { | |
| case Success(x) => println(x) | |
| case Failure(_) => println("I failed to produce THE answer :(") | |
| // ** In the case of a failure, we just keep going; the failure gets passed along | |
| } | |
| Await.ready(calc, 5 seconds) | |
| } | |
| def main(args: Array[String]) { | |
| testAsyncWork | |
| testAsyncChaining | |
| testAsyncChainingForComp | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment