Issue with Project Reactor's or() operator usage

强颜欢笑 提交于 2019-12-02 04:55:22

You misunderstand or() - it takes the first result emitted from either publisher. That's very different from the first item emitted - if one of the Mono objects emits an onComplete() result without returning anything, then, as is happening in your case, you'll get that result with nothing emitted.

You can see this behaviour if you do something like Mono.<String>empty().delaySubscription(Duration.ofMillis(100)).or(Mono.just("hello")); instead, which will almost certainly pass (as the onComplete() result of the emtpy Mono is delayed sufficiently for the other Mono to emit an item first.)

However, the method you're after is switchIfEmpty(), which (as the name suggests) will wait for the first Mono to complete, then fallback to the second if the first returns an empty result:

@Test
public void orTest() {
    Mono<String> chain = Mono.<String>empty().switchIfEmpty(Mono.just("hello"));

    StepVerifier.create(chain)
            .expectNext("hello")
            .verifyComplete();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!