Search code examples
springmonospring-webfluxproject-reactorflux

Mono - Flux switchIfEmpty and onErrorResume


In project reactor is it possible to implement a stream with switchIfEmpty and onErrorResume at the same time?

infoRepository.findById(id); //returns Mono<Info>

in case of empty or error then switch to the same backup stream?


Solution

  • There's no single operator that does these things together, but you can trivially switch to an empty publisher on an error, then handle both cases through switchIfEmpty like:

    infoRepository.findById(id)
                  .onErrorResume(e -> Mono.empty())
                  .switchIfEmpty(newPublisher);