I'm looking for a way to retrieve an alternative Mono in case the original one is empty. The closest one I found is Mono.switchIfEmpty
, but my problem with it is that I can't pass a lambda expression to it so it's being called even when the Mono has a non-empty value. This is sort of like Optional.orElse
vs Optional.orElseGet
.
Here is a sample:
return someService.findSomeElements() // returns a Flux<Element>
.filter(this::checkIfMatches)
.singleOrEmpty()
.switchIfEmpty(...); // <-- I want to use lambda here
Wrap the alternative Mono
in a Mono.defer
inside the switchIfEmpty
and it will be lazily instantiated only when the original is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With