reactive-programmingspring-webfluxspring-webclientwebfluxspring5

how to merge the response of webClient call after calling 5 times and save the complete response in DB


i have scenario like: i have to check the table if entry is available in DB then if available i need to call the same external api n times using webclient, collect all the response and save them in DB. if entry is not available in DB call the old flow.

here is my implementation. need suggestions to improve it. without for-each

public Mono<List<ResponseObject>> getdata(String id, Req obj) {
    return isEntryInDB(id) //checking the entry in DB
        .flatMap(
            x -> {
              final List<Mono<ResponseObject>> responseList = new ArrayList<>();
              IntStream.range(0, obj.getQuantity()) // quantity decides how many times api call t happen
                  .forEach(
                      i -> {
                        Mono<ResponseObject> responseMono =
                            webClientCall(
                                    id,
                                    req.getType())
                                .map(
                                  res ->
                                        MapperForMappingDataToDesriedFormat(res));
                        responseList.add(responseMono);
                      });
              return saveToDb(responseList);
            })
        .switchIfEmpty(oldFlow(id, req));  //if DB entry is not there take this existing flow.

need some suggestions to improve it without using foreach.


Solution

  • I would avoid using IntStream and rather use native operator to reactor called Flux in this case.

    You can replace, InsStream.range with Flux.range. Something like this:

    return isEntryPresent("123")
                    .flatMapMany(s -> Flux.range(0, obj.getQuantity())
                            .flatMap(this::callApi))
                    .collectList()
                    .flatMap(this::saveToDb)
                    .switchIfEmpty(Mono.defer(() ->oldFlow(id, req)));
    
        private Mono<Object> saveToDb(List<String> stringList){
            return Mono.just("done");
        }
        private Mono<String> callApi(int id) {
            return Mono.just("iterating" + id);
        }
    
        private Mono<String> isEntryPresent(String id) {
            return Mono.just("string");
        }