rx-javareactive-programmingrx-java2micronautmicronaut-rest

What should be the return type of reactive controller methods in Micronaut?


I am new to Micronaut and looking at the samples I can't figure the right return type for controller methods. I need an API method that accepts a String, validates the input, fetches some data from database and returns ObjectA for successful processing, ObjectB for handled exceptions in business logic and ObjectC for unhandled/runtime exceptions.

public HttpResponse mapItem(@Valid final CustomRequest request,
                            final HttpRequest httpRequest) {
    //@Valid can throw exceptions
    return service.process(request);    //can throw exception
}
  1. Should the return type be HttpResponse, HttpResponse<ObjectA> or Single<HttpResponse<ObjectA>> or Maybe<HttpResponse<ObjectA>?
  2. Is there a way I can explicitly declare the error type of Single or Maybe to help the code reviewers understand this API can return ObjectB or ObjectC in case of errors?
  3. Will the RX disposable auto-close and cleanup resources in case an unhandled exception happens? I also work on Android where we need to close the streams manually.

Solution

  • Question 1:

    Should the return type be HttpResponse, HttpResponse or Single<HttpResponse> or Maybe<HttpResponse?

    From https://docs.micronaut.io/2.4.2/guide/#reactiveResponses:

    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.

    For example:

        @Post("/saveReactive")
        public Single<HttpResponse<Person>> save(@Body Single<Person> person) { 
            return person.map(p -> {
                        inMemoryDatastore.put(p.getFirstName(), p); 
                        return HttpResponse.created(p); 
                    }
            );
        }
    

    Question 2:

    Is there a way I can explicitly declare the error type of Single or Maybe to help the code reviewers understand this API can return ObjectB or ObjectC in case of errors?

    Depending on what you really mean by that, possibly. https://docs.micronaut.io/2.4.2/guide/#localErrorHandling describes a number of error handling options, including error handlers that return something like HttpResponse<JsonError>.

    Question 3:

    Will the RX disposable auto-close and cleanup resources in case an unhandled exception happens? I also work on Android where we need to close the streams manually.

    For resources managed by Micronaut, yes, but not necessarily all resources. You could write code that creates lots of resources and Micronaut wouldn't necessarily even be able to know about those.