Home > Software design >  Mono returning empty list
Mono returning empty list

Time:10-29

I am trying to call getProductContract() but it returns an empty list. I think that's because the Mono is not being executed.

Can someone pls help me on how to execute the calls so that I get the populated resultList back?

Sample code

//Controller.java:

service.getProductContract()


// Service.java
public Mono<List<ProductContract>> getProductContract() {
        Set<String> productIdList = new HashSet<>();
        productIdList.add("p123");
        productIdList.add("p456");

        List<ProductContract> resultList = new ArrayList<>();

        productIdList.forEach(productId -> prodRepository.getProductDetails(productId)
                .flatMap(productDetail -> prodRepository.getProductContracts(productDetail.getProductContractId()))
                .mapNotNull(contracts -> resultList.add(contracts.stream().findFirst().isPresent()? contracts.stream().findFirst().get():null))
                .subscribeOn(Schedulers.boundedElastic())
        );
       log.info("size {}",String.valueOf(resultList.size())); //-> Size is ZERO
       return Mono.just(resultList);

    }

// Repository.java

public Mono<List<ProductContract>> getProductContracts (String contractId){...} // can return multiple contacts for 1 id

public Mono<String> getProductDetails(String productId){...}

CodePudding user response:

This productIdList....flapMap... block is executed asynchronously, when printing the size in the log.info, it was zero indicates the execution is not completed.

A better way to assemble all resources in your case is like this.

return Flux.fromIterable(productIdList)
     .flatMap(productId -> prodRepository.getProductDetails(productId))
     .flatMap(p-> ....getContacts)
     .map(....build a contact dto instance...)
     

If you want to return a Mono<List<ContactDto>>, just call Flux.collectList.

  • Related