Scala Async Macro

Scala has an async macro that manages your Futures and Awaits to compose asynchronous results.

The basic idea is to do something like this (stolen from here):

import ExecutionContext.Implicits.global
import scala.async.Async.{async, await}

val future = async {
  val f1 = async { ...; true }
  val f2 = async { ...; 42 }
  if (await(f1)) await(f2) else 0
}

or some variation of this pattern. Depending on how you you structure your calls to await or when you create (and start) the future, you may get parallelism or just non-blocking.

Since nearly all remote calls should be considered "slow", the other example on the site where I found the first example above is:

def combined: Future[Int] = async {
  val future1 = slowCalcFuture
  val future2 = slowCalcFuture
  await(future1) + await(future2)
}

There is not more more to say here. Since dispatch returns a future, just use the async macro to compose your futures as needed for your application.

The dispatch documentation discusses for comprehensions for composing your futures, and the async macro is equivalent to that but with nicer and clear syntax, at least in my opinion.

As final proof that this works, you can add a route to our example server that delays a specific amount of time then returns the delay parameter that is provided in the URL of the GET request:

 ~ path("delay" / LongNumber) { n =>
        withoutRequestTimeout {
          get {
            import scala.concurrent._
            import scala.concurrent.duration._
            println(s"Delaying $n milliseconds.")           
            complete(akka.pattern.after(n.millis, system.scheduler)(Future { n.toString }))
          }
        }
      }

By calling localhost:9000/delay/10000, you can delay the response by 10 seconds and the number 10000 is returned in the body. Hence, in amm we could do something like:

load.ivy("org.scala-lang.modules" %% "scala-async" % "latest.release")
load.ivy("net.databinder.dispatch" %% "dispatch-core" % "0.11.3")

import scala.async.Async._
import dispatch._, Defaults._
import scala.concurrent.Await
import scala.concurrent.duration._

def callit(n: Long) =
  Http(url(s"http://localhost:9000/delay/$n") OK as.String).map(_.toLong)

val d1 = 5000
val d2 = 2000

println(s"Delay 1 is $d1, Delay 2 is $d2")

val resultFuture = async {
  val future1 = callit(d1)
  val future2 = callit(d2)
  await(future1) + await(future2)
}
resultFuture onComplete { r => println(s"Result $r")}

and you get a result of

Result Success(7000)

Last updated