Issue with Project Reactor's or() operator usage

别说谁变了你拦得住时间么 提交于 2019-11-28 11:20:54

问题


I would like to chain Monos and emit the first non-empty of them. I thought the or() operator was designed for this purpose.

Here is my chain of Monos: first one is empty and second one should emit "hello".

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

    StepVerifier.create(
        chain
    )
        .expectNext("hello")
        .verifyComplete();
}

However, I get the following failure:

java.lang.AssertionError: expectation "expectNext(hello)" failed (expected: onNext(hello); actual: onComplete())

Can someone please help? What I am getting wrong here?


回答1:


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();
}


来源:https://stackoverflow.com/questions/57825533/issue-with-project-reactors-or-operator-usage

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