Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between ResponseEntity<Mono> and Mono<ResponseEntity> as a return type of a rest controller

In Spring Webflux, what's the difference between ResponseEntity<Mono> versus Mono<ResponseEntity> as a return type of a rest controller?

When is the most appropriate to what?

Following up on this question, let's say I need to return a list, or let's say several elements of Foo, there are many examples of returning Flux. Would it make sense to return ResponseEntity<Flux> or Flux<ResponseEntity>?

When I'm looking for this question, I found the same question posted here: https://github.com/spring-projects/spring-framework/issues/22614, but no answer, I searched spring docs, but find no info.

Thanks for the help.

like image 281
Chaofan Zhang Avatar asked Sep 03 '19 09:09

Chaofan Zhang


People also ask

What is the return type of ResponseEntity?

A ResponseEntity is returned. We give ResponseEntity a custom status code, headers, and a body. With @ResponseBody , only the body is returned. The headers and status code are provided by Spring.

Why do we use ResponseEntity in a restful service?

ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response. If we want to use it, we have to return it from the endpoint; Spring takes care of the rest.

What is a mono response?

A Mono is a stream of 0 to 1 element, whereas a Flux is a stream of 0 to N elements. This difference in the semantics of these two streams is very useful, as for example making a request to a http server expects to receive 0 or 1 response, it would be inappropriate to use a Flux in this case.

What is the difference between ResponseBody and ResponseEntity?

ResponseEntity<> is a generic class with a type parameter, you can specify what type of object to be serialized into the response body. @ResponseBody is an annotation, indicates that the return value of a method will be serialized into the body of the HTTP response.


1 Answers

Here are the various options you can make with a ResponseEntity return value:

  • ResponseEntity<Mono<T>> or ResponseEntity<Flux<T>> -- this makes the response status and headers known immediately while the body is provided asynchronously at a later point. Whether the body is Mono or Flux depends on how many values the response has.
  • Mono<ResponseEntity<T>> -- this provides all three -- response status, headers, and body, asynchronously at a later point. IT allows the response status and headers to vary depending on the outcome of asynchronous request handling.
  • Mono<ResponseEntity<Mono<T>>> or Mono<ResponseEntity<Flux<T>>> are also possible but less common. They provide the response status and headers asynchronously first and then the response body, also asynchronously at a second point later.
like image 65
Rossen Stoyanchev Avatar answered Oct 20 '22 21:10

Rossen Stoyanchev