in

Spring boot response is returned before for loop is finished webflux


I have a piece of code that I’m converting from procedural to functional basically from java spring to webflux spring boot

So the method is quite complicated with a lot of if/else

private static Map<Integer, Mono<ResponseDTO>> buildResponseMap(ServerRequest serverRequest ) {
  Map<Integer, Mono<ResponseDTO>> monoResponsesList = new HashMap<>();
  Mono<ResponseDTO> monoResponse;

  if (serverRequest.getType().equals("wood") ) {
        int index = 0;
        for (Item item: serverRequest.getItems()) {
            // do some checks
            ItemResponseDTO itemResponse = ResponseUtil.createResponse(serverRequest , someData);
            if (itemResponse.hasErrors()) {
              monoResponse = Mono.just(new ResponseDTO(itemResponse , itemResponse.getErrors()));
            } else {
              monoResponse = Mono.just(new ResponseDTO(itemResponse ));
            }
            monoResponsesList.put(index ++, monoResponse);
       }
       
       // **FIRST Return**
       return monoResponsesList;
  }

  //some other code
  ItemResponseDTO itemResponse = ResponseUtil.createResponse(serverRequest, someOtherData);
  monoResponse = Mono.just(new ResponseDTO(itemResponse ));
  monoResponsesList.put(index++, monoResponse);
  return monoResponsesList;
}

Then this method I call it:

public Mono<ServiceResponse> getItemsResponse(ServerRequest serverRequest) {
        ServiceResponse serviceResponse= new ServiceResponse();
        Collection<Mono<ResponseDTO>> responsesList= buildResponseMap(serverRequest).values();
        responsesList.forEach(response-> response.subscribe(
                responseValue -> {
                    serviceResponse.getData().add(responseValue );
                },
                Throwable::printStackTrace
        ));
        return Mono.just(serviceResponse);
    }

The problem is that when I call method buildResponseMap(serverRequest) if the monoResponsesList is returned on FIRST Return inside if, the list doesn’t wait for the for loop execution and it is returned before the loop is completed/finished.

Can somebody help me on this please, I found a lot of examples with web flux but none with multiple if/else and for loops?

Can somebody help me with how to make this code work so the response is returned when the loop is completed? I’m blocked.



Source: https://stackoverflow.com/questions/70628276/spring-boot-response-is-returned-before-for-loop-is-finished-webflux

Todo backend with python

How can i get hashmap’s key inside of the hashmap