Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazily evaluated switchIfEmpty for Project Reactor's Mono

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 
like image 714
Balazs Avatar asked Feb 05 '18 14:02

Balazs


1 Answers

Wrap the alternative Mono in a Mono.defer inside the switchIfEmpty and it will be lazily instantiated only when the original is empty.

like image 99
Simon Baslé Avatar answered Sep 18 '22 10:09

Simon Baslé