Search code examples
javaspringspring-webfluxprojectproject-reactor

How to handle nested subscriptions in Spring webflux


I have a requirement in which I need to perform a sequence of 3 method calls each of which returns a Mono.

   Mono<WeightResponse> weightService() 
   Mono<PriceResponse> priceService(WeightResponse wr) 
   Mono<DispatchResponse> dispatchService(PriceResponse pr)

These 3 method calls need to be done in chronological order.

This is what I have tried to come up with. I am yet to compete and test this functionality end to end. I am looking for advice on how to handle this type of scenario in Spring Reactor? There is subscription inside subscription inside subscription. Is this the right approach to handle such a scenario? Could there be any side effects of such nested subscriptions?

weightService().subscribe(wr -> {
      priceService(wr).subscribe (pr -> {
        dispatchService(pr).subscribe (dr -> {
            System.out.println("Dispatch Done!");
          },
          e -> log.error("error in dispatch {}", e);
        );
       },
       e -> log.error("error in pricing {}", e);
      );
     },
     e -> log.error("error in weight calculation {}", e);
   );
      

Solution

  • You should not subscribe explicitly. Typically you need to construct reactive flow and the framework like spring-webflux will subscribe to it.

    In the following example flatMap would subscribe internally and you could chain response to use it in the next operator.

    Mono<DispatchResponse> execute() {
        return weightService()
                .flatMap(wr -> priceService(wr))
                .flatMap(pr -> dispatchService(pr));
    }