In ProjectReactor or Reactive Streams, Nothing Happens Until You subscribe().
Reactive streams data flow will not happen unless until someone subscribe to it, but I see for all REST APIs like finds, save and inserts are not calling subscribe explicitly but data is flowing between producer and subscribers.
@RestController
class PersonController {
private final PersonRepository repository;
public PersonController(PersonRepository repository) {
this.repository = repository;
}
@GetMapping("/all")
public Flux<Person> index() {
return repository.findAll();
}
@GetMapping("/people")
Flux<String> namesByLastname(@RequestParam Mono<String> lastname) {
Flux<Person> result = repository.findByLastname(lastname);
return result.map(it -> it.getFullName());
}
@PostMapping("/people")
Flux<People> AddPeople(@RequestBody Flux<Person> people) {
return repository.saveAll(people);
}
}
why do we no need to call subscribe for REST Endpoints to start a data flow in Project Reactor?
How REST endpoints (HTTP requests) are auto-subscribing to Reactive Streams for data flow when i call from browser?
am i missing something here ?
You're right - when your application is setting up a Flux
/Mono
reactive pipeline, nothing in that pipeline is executed until something subscribe
to it.
Here's what's happening during a request/response exchange in Spring WebFlux:
The lowest contract in Spring WebFlux is HttpHandler
- it's the contract that interfaces with the underlying server.
In the case of Reactor Netty, this server already supports the reactive streams API and the subscription is natively done by the server.
For other Servlet-based servers, we're using a reactive streams bridge to Servlet 3.1. In ServletHttpHandlerAdapter
, we're bridging between the reactive streams world and the async I/O Servlet API - the subscription actually happens within that bridge.
Also: note that we don't usually subscribe
to the value returned by WebClient
; you can only do that if you're not in the middle of a reactive pipeline (i.e. not in the middle of a Controller handler). In those cases, we usually plug that into a reactive operator in the middle of the pipeline; if you don't, you'll have no guarantee whatsoever about when you'll get the HTTP client response - this totally decouples that call from the rest of your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With