首页 > 解决方案 > 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?

标签: monospring-webfluxproject-reactor

解决方案


这仍然是 java:这个调用someApi.fetch(param)不是在 lambda 内部完成的,所以它不能偷懒。执行到达该then行的那一刻,您的fetch方法被调用。运营商是量身定制的Flux.defer,可以包装该呼叫并使其变得懒惰。


推荐阅读