Skip to content

Instantly share code, notes, and snippets.

@cer
Last active December 16, 2015 07:18
Show Gist options
  • Save cer/5397346 to your computer and use it in GitHub Desktop.
Save cer/5397346 to your computer and use it in GitHub Desktop.
Using Scala Futures to reimplement the Java Future examples used to provide the motivation for Netflix RxJava - https://gist.github.com/benjchristensen/4671081#file-futuresb-java-L163 - in the announcement: http://techblog.netflix.com/2013/02/rxjava-netflix-api.html The code compares quite nicely with RxJava
@RunWith(classOf[JUnitRunner])
class Example1Test extends FunSuite with ShouldMatchers {
// Services that return Futures
def serviceA() = Future { 7 }
def serviceC(x : Int) = Future { 2 * x }
def serviceB() = Future { 9}
def serviceD(x : Int) = Future { 5 * x}
def serviceE(x : Int) = Future { 4 * x}
test("using flatMap and map") {
val f1 = serviceA()
val f3 = f1.flatMap{ serviceC }
val f2 = serviceB()
val f4 = f2.flatMap{serviceD }
val f5 = f2.flatMap{serviceE }
val z0 = (f3 zip f4 zip f5) map { x => (x._1._1, x._1._2, x._2)}
val z = Await.result(z0, 10 second)
z should equal((14,45,36))
}
test("call many services with futures and map()") {
def doMoreWork(x : Int) = x * x
val f1s = (1 to 10).map(serviceC)
val f2s = f1s map { _.map(doMoreWork) }
val f3 = Future.sequence(f2s)
val r = Await.result(f3, 1 seconds)
r should equal(List(4, 16, 36, 64, 100, 144, 196, 256, 324, 400))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment