Last active
December 28, 2015 20:29
-
-
Save archie/7557376 to your computer and use it in GitHub Desktop.
Playing with futures in Scala
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.duration._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import math.random | |
object Zoo extends App { | |
val animals = List("monkey", "donkey", "giraffe").map { animal => | |
for { | |
fed <- feed(animal) | |
washedAndFed <- wash(fed) | |
} yield washedAndFed | |
} | |
def feed(animal: String) = Future { | |
Thread.sleep(150) // take some time | |
animal | |
} | |
def wash(animal: String) = Future { | |
Thread.sleep(250) // take some time | |
if ((random * 100).toInt > 75) throw new Exception // the animal got angry | |
else animal | |
} | |
val cleanedAndFedAnimals = Future.sequence(animals) | |
cleanedAndFedAnimals onComplete { | |
case Success(res) => println("Happy animals: " + res.mkString(", ")) | |
case Failure(_) => println("Sad zookeeper :(") | |
} | |
Thread.sleep(500) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment