Madeyedexter
Madeyedexter

Reputation: 1193

Mono.switchIfEmpty with Mono.then evaluation order

I build the reactive pipeline like this on netty server with spring web-flux:

someService.getSettings(key) //Mono<Settings>
        .filter(Settings::isEnabled)
        .switchIfEmpty(Mono.error(
            new Exception("Setting is disabled.")
        )).then(/*Mono representing API fetch*/ someApi.fetch(param));

As per my understanding, whenever the Settings::isEnabled would return false, the pipeline would be empty and I will get a Mono representing error. However, this behavior does not happens. My someApi.fetch(param) call always fires without the filter Mono being completed. So even if Settings::isEnabled is false or true, someApi.fetch(param) is always fired without completion of Mono.filter.

How do I make sure that error is thrown if filter returns empty Mono and the fetch call happens only when I have checked that the setting is not disabled?

Upvotes: 2

Views: 1970

Answers (1)

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

this is still java: this call to someApi.fetch(param) is not done inside a lambda, so it can't be lazy. the moment the execution reaches the then line, your fetch method is called. the Flux.defer operator is tailor-made to wrap that call and make it lazy.

Upvotes: 1

Related Questions