Streaming Data
Not having to wait for the full response to be complete also provides another benefit - we can even send intermediate results when they are ready by streaming data!
This can be achieved in multiple ways, one of them being using the ResponseBodyEmitter. There are specialized subclasses of it like the SseEmitter that can be used for streaming mechanisms like server-sent events (SSE).
ServerSentEvents.png
Similar to the DeferredResult, the request handler returns immediately after creating the ResopnseBodyEmitter and frees up the servlet worker thread. Only this time the application logic can publish multiple results which can be immediately flushed to the client without closing the connection. This is usually wrapped in the SSE format mentioned above or simply using newline delimited json objects.
The pseudo-code for our ReturnValueHandler in spring would look like this
We set the content-type of the response to a streaming format - in this example SSE - and put the request into async mode.
The emitter itself would provide the following two (oversimplified) methods:
Every time the application code wants to send an object it is converted to the streaming format (here SSE) and flushed to the response output stream. Once the request is completed, an ASYNC dispatch is triggered, cleaning up the request.
Another way to stream data would be making use of the reactive type Flux which internally works slightly differently than our ResponseBodyEmitter but will produce the same result.