'Perform two queries at the same time (reactive)

I know it is asynchronous and therefore the values I want to save will be null (I checked). How can I fix this so that everything is saved correctly?

I want to save a Document and at the same time get that ID generated by MongoDB to save to another API.

public Mono<BankAccountDTO> save(BankAccountDTO bankAccount) {
    
    return mongoRepository.save(AppUtils.dtoToEntity(bankAccount))
        .doOnNext(d -> {
            
            CustomerRoleDTO cDto = new CustomerRoleDTO();
            cDto.setBankAccountid(d.getId());
            cDto.setClientId(bankAccount.getCustomerId());
            
            webClient.post()
                .uri("http://localhost:9292/api/v1/example")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .body(Mono.just(cDto), CustomerRoleDTO.class)
                .retrieve()
                .bodyToMono(CustomerRoleDTO.class);
            
        }).map(AppUtils::entityToDTO);

}


Solution 1:[1]

you are breaking the chain by not handling the return from your wbClient call, so that reactor can't fulfill assembly time.

(i have not checked against a compiler, but something like this)

public Mono<BankAccountDTO> save(BankAccountDTO bankAccount) {
    return mongoRepository.save(AppUtils.dtoToEntity(bankAccount))
        .flatMap(d -> {
            
        CustomerRoleDTO cDto = new CustomerRoleDTO();
        cDto.setBankAccountid(d.getId());
        cDto.setClientId(bankAccount.getCustomerId());
            
        // you cant ignore the return
        return webClient.post()
                .uri("http://localhost:9292/api/v1/example")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .body(Mono.just(cDto), CustomerRoleDTO.class)
                .retrieve()
                .bodyToMono(CustomerRoleDTO.class)
                .thenReturn(d);
    });
}

here you can read more about assembly time.

Assembly vs Subscription

Solution 2:[2]

Use flatmap instead of doOnNext

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Toerktumlare
Solution 2 Yauhen Balykin