+doc #18012 add handleWithAsync documentation + examples

This commit is contained in:
Johannes Rudolph 2015-07-17 14:52:38 +02:00
parent 4fe85b8b56
commit b2c38444b3
2 changed files with 124 additions and 2 deletions

View file

@ -102,4 +102,42 @@ static methods. The referenced method must be publicly accessible.
Deferring Result Creation
-------------------------
TODO
Sometimes a handler cannot directly complete the request but needs to do some processing asynchronously. In this case
the completion of a request needs to be deferred until the result has been generated. This is supported by the routing
DSL in two ways: either you can use one of the ``handleWithAsyncN`` methods passing an ``AsyncHandlerN`` which
returns a ``Future<RouteResult>``, i.e. an eventual ``RouteResult``, or you can also use a regular handler as shown
above and use ``RequestContext.completeWith`` for completion which takes an ``Future<RouteResult>`` as an argument.
This is demonstrated in the following example. Consider a asynchronous service defined like this
(making use of Java 8 lambdas):
.. includecode:: /../../akka-http-tests-java8/src/test/java/docs/http/javadsl/server/HandlerExampleDocTest.java
:include: async-service-definition
Here the calculator runs the actual calculation in the background and only eventually returns the result. The HTTP
service should provide a front-end to that service without having to block while waiting for the results. As explained
above this can be done in two ways.
First, you can use ``handleWithAsyncN`` to be able to return a ``Future<RouteResult>``:
.. includecode:: /../../akka-http-tests-java8/src/test/java/docs/http/javadsl/server/HandlerExampleDocTest.java
:include: async-handler-1
The handler invokes the service and then maps the calculation result to a ``RouteResult`` using ``Future.map`` and
returns the resulting ``Future<RouteResult>``.
Otherwise, you can also still use ``handleWithN`` and use ``RequestContext.completeWith`` to "convert" a
``Future<RouteResult>`` into a ``RouteResult`` as shown here:
.. includecode:: /../../akka-http-tests-java8/src/test/java/docs/http/javadsl/server/HandlerExampleDocTest.java
:include: async-handler-2
Using this style, you can decide in your handler if you want to return a direct synchronous result or if you need
to defer completion.
Both alternatives will not block and show the same runtime behavior.
Here's the complete example:
.. includecode:: /../../akka-http-tests-java8/src/test/java/docs/http/javadsl/server/HandlerExampleDocTest.java
:include: async-example-full