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?
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