Search code examples
javaspring-webfluxreactive-programmingreactive

Call Different Method in reactive pipeline


I have a use case where I have to call two different methods in a reactive pipeline Java 8 on a post-API call.

1st Method: will insert data in a master table and will return the pk of that table insertion.

2nd Method: this method will insert data in the mapping table which will use the pk received from 1st method.

I try to do that Mono.zip, but that did not work as Zip is calling both methods simultaneously and is not able to pass method 1 output to 2nd method input.


Solution

  • You can easily do it using the map or flatMap operator, depending on what type of repository you have - reactive or not reactive.

    Here is examples for both cases:

    public class YourService {
        private final YourRepository repository;
        private final YourReactiveRepository reactiveRepository;
    
        void doAction() {
            Mono.fromCallable(() -> repository.saveToMainTable("main data"))
                .map(mainTableId -> repository.saveToSecondaryTable(mainTableId, "secondary data"))
                .subscribeOn(Schedulers.boundedElastic())
                .subscribe();
        }
    
        void doActionWithReactiveRepository() {
            reactiveRepository.saveToMainTable("main data")
                .flatMap(mainTableId -> reactiveRepository.saveToSecondaryTable(mainTableId, "secondary data"))
                .subscribe();
        }
    
        interface YourRepository {
            int saveToMainTable(String someData);
            boolean saveToSecondaryTable(int mainTableId, String someData);
        }
    
        interface YourReactiveRepository {
            Mono<Integer> saveToMainTable(String someData);
            Mono<Boolean> saveToSecondaryTable(int mainTableId, String someData);
        }
    }
    

    You can read more about map here and about flatMap here