按顺序/并行执行Monos

huangapple go评论71阅读模式
英文:

Execute Monos sequentially/parallel

问题

我有这样的情况

    Mono<List<String>> resultAMono = listA();
    Mono<Void> resultBMono = loadB(resultAMono.block());
    Mono<Void> resultCMono = loadC();

我想按顺序执行resultAMono而resultBMono和resultCMono并行执行因为resultBMono依赖于resultAMono的结果
英文:

I have this situation:

Mono&lt;List&lt;String&gt;&gt; resultAMono = listA();
Mono&lt;Void&gt; resultBMono = loadB(resultAMono.block());
Mono&lt;Void&gt; resultCMono = loadC();

I want to execute resultAMono sequentially, and the resultBMono and resultCMono parallelly, because resultBMono depends of the result of resultAMono

答案1

得分: 1

不需要在这里block。在响应式编程中,您需要构建一个结合不同操作符的流。

Mono<Void> res = resultAMono
        .flatMap(a -> Flux.merge(loadB(a), loadC()).then());

在这里使用Flux.merge是因为loadBloadC都返回Mono<Void>,而我们不需要结果。

如果需要结果,可以使用Mono.zip来并行解析发布者。

Mono<Tuple2<B, C>> res = resultAMono
        .flatMap(a -> Mono.zip(loadB(a), loadC()));

Flux.mergeMono.zip都会急切地订阅发布者。

英文:

You don't need to block here. In reactive you need to build a flow combining different operators

Mono&lt;Void&gt; res = resultAMono
        .flatMap(a -&gt; Flux.merge(loadB(a), loadC()).then());

We are using Flux.merge here because both loadB & loadC return Mono&lt;Void&gt; and we don't need results.

In case results are needed Mono&lt;B&gt; loadB(A a) & Mono&lt;C&gt; loadC() we can use Mono.zip to resolve publishers in parallel.

Mono&lt;Tuple2&lt;B, C&gt;&gt; res = resultAMono
        .flatMap(a -&gt; Mono.zip(loadB(a), loadC()));

Both Flux.merge & Mono.zip subscribes to publishers eagerly.

huangapple
  • 本文由 发表于 2023年3月1日 15:55:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定