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();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…