6.13.2 Reactive Responses

The previous section introduced the notion of Reactive programming using Project Reactor and Micronaut.

Micronaut supports returning common reactive types such as reactor:Mono[] (or Single Maybe Observable types from RxJava), an instance of Publisher or CompletableFuture from any controller method.

To use Project Reactor‘s Flux or Mono you need to add the Micronaut Reactor dependency to your project to include the necessary converters.
To use RxJava‘s Flowable, Single or Maybe you need to add the Micronaut RxJava dependency to your project to include the necessary converters.

The argument designated as the body of the request using the Body annotation can also be a reactive type or a CompletableFuture.

When returning a reactive type, Micronaut subscribes to the returned reactive type on the same thread as the request (a Netty Event Loop thread). It is therefore important that if you perform any blocking operations, you offload those operations to an appropriately configured thread pool, for example using the Project Reactor or RxJava subscribeOn(..) facility or @ExecuteOn.

See the section on Configuring Thread Pools for information on the thread pools that Micronaut sets up and how to configure them.

To summarize, the following table illustrates some common response types and their handling:

Table 1. Micronaut Response Types
TypeDescriptionExample Signature

Publisher

Any type that implements the Publisher interface

Publisher<String> hello()

CompletableFuture

A Java CompletableFuture instance

CompletableFuture<String> hello()

HttpResponse

An HttpResponse and optional response body

HttpResponse<Publisher<String>> hello()

CharSequence

Any implementation of CharSequence

String hello()

T

Any simple POJO type

Book show()

When returning a Reactive type, its type affects the returned response. For example, when returning a reactor:Flux[], Micronaut cannot know the size of the response, so Transfer-Encoding type of Chunked is used. Whilst for types that emit a single result such as reactor:Mono[] the Content-Length header is populated.