Dispatch's Future enhancements

dispatch has added a few enhancements to the standard scala Future to make processing responses easier.

Since a Future can result in either an Exception (an error) or a value (your result), the dispatch enhancements can cast your Future to a scala Either. A scala Either is a co-product, either its one value or the other. A scala product is like a tuple, you can have both values at the same time, which is really like an union type in other programming languages.

So with Either, if you could cast your Future to an Either, you could then pattern match or do other things on it to handle your results.

Anytime you have a Future, you can use dispatch's either method to enhance it:

val yourEither = myDispatchFuture.either
either match { 
...
}

or you could take projections of the Either. A projection "biases" your result so you can map or flatMap it. A good description of projections is here.

You can also print out the value of the Future easily using dispatch's myDispatchFuture.print or wait for the result on your current thread using myDispatchFuture() (although as often noted you should structure your program to not need Await). As a side note, I often just do a myDispatchFuture onComplete println to allow my program to print the result, whether error or valid value, when it completes. Using onComplete results in a non-blocking "callback" to be registered on the Future.

You can compose results using the following scala provided functions:

  • map

  • flatMap

  • recover (which is like map for errors)

  • recoverWith (which is like flatMap for errors)

because in most cases, I need to return a default value or perhaps some error message as the return value. These methods allow me to compose more cleanly than using Either which sometimes be awkward but is dependent on your application needs.

There are some other enhancements as well in dispatch including obtaining an Option and a flatten. Most of the functions around this enhancement require an ExecutionContext to run since they may involve return another Future that was composed with the original Future you had. Again, you can use the context in Defaults._ or provide your own, but be careful about what threads you run the composition on as jumping thread pools could negatively impact performance.

Last updated