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.
We’ll start with a very simple request.
import dispatch._, Defaults._ val svc = url("http://api.hostip.info/country.php") 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
country represents a future of the string rather
than the string itself.
You can act on the response once it’s available with a for-expression.
for (c <- country) println(c)
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.
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.