6.11.2 Reactive Responses

The previous section introduced the notion of Reactive programming using RxJava 2.x and Micronaut.

Micronaut supports returning common reactive types such as Single or Observable (or the Mono type from Reactor 3.x), an instance of Publisher or CompletableFuture from any controller method.

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

Micronaut also uses these types to influence which thread pool to execute the method on. If the request is considered non-blocking (because it returns a non-blocking type) then the Netty event loop thread will be used to execute the method.

If the method is considered blocking then the method is executed on the I/O thread pool, which Micronaut creates at startup.

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

Flowable<String> hello()

CompletableFuture

A Java CompletableFuture instance

CompletableFuture<String> hello()

HttpResponse

An HttpResponse and optional response body

HttpResponse<Flowable<String>> hello()

CharSequence

Any implementation of CharSequence

String hello()

T

Any simple POJO type

Book show()

When returning a Reactive type, the type of reactive type has an impact on the response returned. For example, when returning a Flowable, Micronaut can not know the size of the response, so Transfer-Encoding type of Chunked is used. Whilst for types that emit a single result such as Single the Content-Length header will be populated.