Project Reactor 的 or() 运算符使用问题 [英] Issue with Project Reactor's or() operator usage

查看:21
本文介绍了Project Reactor 的 or() 运算符使用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想链接 Mono 并发出它们中的第一个非空.我认为 or() 运算符就是为此目的而设计的.

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

这是我的 Mono 链:第一个是空的,第二个应该发出hello".

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?

推荐答案

你误解了 or() - 它需要 第一个结果来自任一发布者.这与发出的第一个 item 非常不同 - 如果其中一个 Mono 对象发出 onComplete() 结果而不返回任何内容,那么,照原样发生在你的情况下,你会得到这个结果,没有任何发射.

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.

如果您执行类似 Mono.<String>empty().delaySubscription(Duration.ofMillis(100)).or(Mono.just("hello"));Mono.<String>empty().delaySubscription(Duration.ofMillis(100)).or(Mono.just("hello")); 相反,它几乎肯定会通过(因为 emtpy MonoonComplete() 结果被延迟到足以让另一个 Mono 发出首先是一个项目.)

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.)

然而,你所追求的方法是 switchIfEmpty(),它(顾名思义)将等待第一个 Mono 完成,然后如果第一个返回空结果,则回退到第二个:

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

这篇关于Project Reactor 的 or() 运算符使用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆