'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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source