16

I am looking at some examples of reactive web applications and i am seeing them like this

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody    
public Mono<Person> findById(...) {
    return exampleService.findById(...);
}

@RequestMapping(method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Person> findAll() {
    Flux<Person> persons = exampleService.findAll();
    return persons;
}

When i am reading about the Mono and Flux in the documentation it mentioned subscribe has to be called for Mono or Flux to emit the data.

So when i run these reactive webapplications locally and using postman/chrome browser when i hit the endpoints i getting the results.

On the service side though endpoints are returning Mono or Flux, how i am seeing the actual results in the browser/postman. Is the browser doing the part of calling the subscribe internally whenever i am hitting the endpoints that return Mono/Flux types?

vjk
  • 2,163
  • 6
  • 28
  • 42

2 Answers2

11

Mono and Flux concepts exist only within your application, while HTTP protocol is used to communicate between your postman/chrome app and your application.
Internal classes of the Spring Webflux framework subscribe to Mono and Flux instances returned by your controller methods and map them to HTTP packets based on the MediaType that you specified in RequestMapping.

Ilya Zinkovich
  • 4,082
  • 4
  • 25
  • 43
  • 1
    So if the media type is something other than event-stream maybe like json, then would the webflux framework call the subscribe on the Mono returned by the controller and block till an oncomplete or onerror is triggered and then return the response to the Client(browser/postman). – vjk Jun 07 '19 at 14:36
  • 2
    yes, that's right. If the return type is Flux and media type is just json, Spring will subscribe to Flux, wait until the last element or an error, and will serialise the whole list of elements in one HTTP response. Infinite Flux will result in timeout on the client side. – Ilya Zinkovich Jun 07 '19 at 14:50
  • Thank you, can you point me to a resource where this is documented. – vjk Jun 07 '19 at 15:16
  • @vjk I don't know where it's described in the documentation. These are just my observations from debugging the webflux apps. – Ilya Zinkovich Jun 07 '19 at 20:11
4

It depends on which server you use.

For instance, Tomcat, Jetty (Servlet 3.1 non-blocking I/O) - ServletHttpHandlerAdapter from org.springframework.http.server.reactive package.

Subscription happens in service method:

@Override
public void service(ServletRequest request, ServletResponse response) throws 
  ServletException, IOException {        
    ...
    HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext, 
        isCompleted, httpRequest);
    this.httpHandler.handle(httpRequest, httpResponse).subscribe(subscriber);
}
Yauhen Balykin
  • 731
  • 5
  • 13