Search code examples
springspring-webfluxreactivespring-mono

Updating Mono object by another Mono object


Dears, I'm a stuck with implementing a function (it is basically an update operation) that's capable of taking a Mono as a param and return an updated version of Mono where:

  • the returned instance derives from a db query;
  • the updated version of Mono contains fields picked by Mono.

This is the sample code (that works from providing directly the object, without using the Mono instance:

public Mono<CompanyDto> updateById(String id, CompanyDto companyDtoMono) {
    return getCompanyById(id).map(companyEntity -> {
        companyEntity.setDescription(companyDtoMono.getDescription());
        companyEntity.setName(companyDtoMono.getName());
        return companyEntity;
    }).flatMap(companyEntity2 -> reactiveNeo4JTemplate.save(companyEntity2)).map(companyEntity -> companyMapper.toDto(companyEntity));

}`

Question is: how can I change the code if the function signature would be

public Mono<CompanyDto> updateById(String id, Mono<CompanyDto> companyDtoMono)

PS:

getCompanyById(id)

returns a

Mono<CompanyEntity>

Thanks, best

FB


Solution

  • There are many solutions for this problem but one of them is using Zip

        public Mono<CompanyDto>  updateById(String id, Mono<CompanyDto> companyDtoMono){
     return    Mono.zip(getCompanyById(id),companyDtoMono,(companyEntity, companyDto) -> {
            companyEntity.setDescription(companyDto.getDescription());
            companyEntity.setName(companyDto.getName());
            return companyEntity;
        })
             .flatMap(companyEntity2 -> reactiveNeo4JTemplate.save(companyEntity2))
             .map(companyEntity -> companyMapper.toDto(companyEntity));
    }