Databinder Dispatch

Dispatch is a library for asynchronous HTTP interaction. It provides a Scala vocabulary for Java’s async-http-client. The latest release version is 0.11.2.

This documentation walks through basic functionality of the library. You may also want to refer to its scaladocs. And for information on Dispatch 0.8.x, see dispatch-classic.

Diving in

If you have sbt installed, Dispatch is two steps away. Open a shell and change to an empty or unimportant directory, then paste:

echo ‘libraryDependencies +=
“net.databinder.dispatch” %% “dispatch-core” % “0.11.2”‘ > build.sbt
sbt console

After “the internet” has downloaded, you’re good to go.

Defining requests

We’ll start with a very simple request.

import dispatch._, Defaults._
val svc = url(“”)
val country = Http(svc OK as.String)

The above defines and initiates a request to the given host where 2xx responses are handled as a string. Since Dispatch is fully asynchronous, country represents a future of the string rather than the string itself.

Deferring action

You can act on the response once it’s available with a for-expression.

for (c <- country)

This for-expression applies to any successful response that is eventually produced. If no successful response is produced, nothing is printed. This is how for-expressions work in general. Consider a more familiar example:

val opt: Option[String] = None
for (o <- opt) println(o) An option may or may not contain a value, just like a future may or may not produce a successful response. But while any given option already knows what it is, a future may not. So the future behaves asynchronously in for-expressions, to avoid holding up operations subsequent that do not depend on its value. Demanding answers As with options, you can require that a future value be available at any time: val c = country() But the wise use of futures defers this operation as long as is practical, or doesn’t perform it at all. To see how, keep reading.


Bargaining with futures
Abstraction over future information
Working with multiple futures
Arbitrarily many futures
A future of success and failure
Success as the only option
Either type will do
Either Future
Defining requests
HTTP methods and parameters

Website development from Charles Brian International
Unraveling for-expressions
Contents in Depth
Combined Pages