Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

reactive programming - Issue with Project Reactor's or() operator usage

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...