Skip to content

Instantly share code, notes, and snippets.

@archie
Last active December 28, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archie/7557376 to your computer and use it in GitHub Desktop.
Save archie/7557376 to your computer and use it in GitHub Desktop.
Playing with futures in Scala
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