Two Handlers Are Better Than One

Dispatch has so many handy response handlers—but what if you want to use two with the same request? You can’t do that with a stream of the response body, since this can only be consumed once, but for headers it’s essential and straightforward.

Header Chaining

The recommended header-handling verb >:+ provides a header Map and a request object to chain a second handler for the body.

http(:/("dispatch.databinder.net") >:+ { (headers, req) =>
  headers("content-type").filter {
    _.contains("text/html")
  }.headOption.map { _ =>
    req </> { nodes => (nodes \\ "h1").text }
  }.getOrElse {
    req >> { _ => "unknown content type" }
  }
})

To facilitate case-insensitive handling, the keys in the header Map are uniformly lowercase.

The function passed to >:+ should produce a second handler for the body of the response. In this case, it produces different response handlers depending on the headers present.

Contents

Dispatch
  1. Try Dispatch
  2. Choose an Executor
  3. Project Setup
  4. Community
  5. A Simple Request
  6. Parsing Responses
  7. Putting It All Together
    1. Two Handlers Are Better Than One
  8. Dispatch in Android
  9. API Reference
  10. Who’s Using Dispatch?
  11. Contents in Depth
  12. Combined Pages
Fork me on GitHub