Created
July 24, 2016 14:46
-
-
Save JoolsF/a9065bdc7b9e0692ae648bd6da8d2e13 to your computer and use it in GitHub Desktop.
Future example 1
This file contains 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.util.{Failure, Success} | |
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global | |
/** | |
* Computation 1 depends on nothing | |
* Computation 1b depends on result of 1 | |
* Computation 2 depends on nothing | |
* | |
* Computation 1b may thrown an exception | |
*/ | |
object TestApp extends App{ | |
val r = scala.util.Random | |
type computation1Result = Int | |
case class ComputationException(e: String) extends Exception | |
val computation1: Future[computation1Result] = Future { | |
Thread.sleep(r.nextInt(2000)) | |
val result = r.nextInt(100) | |
println(s"Computation1 complete with result $result") | |
result | |
} | |
def computation1b(c1: computation1Result): Future[Int] = Future { | |
Thread.sleep(r.nextInt(2000)) | |
if(r.nextInt(2) == 0 ) throw ComputationException(s"computation1b Runtime exception") | |
val result = c1 * r.nextInt(100) | |
println(s"Computation1b complete with result $result") | |
result | |
} | |
val computation2: Future[Int] = Future { | |
Thread.sleep(r.nextInt(200)) | |
val result = r.nextInt(100) | |
println(s"Computation2 complete with result $result") | |
result | |
} | |
val result = for { | |
c1 <- computation1 | |
c1b <- computation1b(c1) | |
c2 <- computation2 | |
} yield(c1 * c1b * c2) | |
result.onComplete(r => r match { | |
case Success(s) => println(s"Success: $s") | |
case Failure(f) => println(s"Failure: $f") | |
}) | |
Thread.sleep(5000) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment