是否可以并行启动 Mono 并汇总结果

编程入门 行业动态 更新时间:2024-10-28 03:25:55
本文介绍了是否可以并行启动 Mono 并汇总结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道可以链接 Mono,例如...

I know it is possible to chain Mono's, for ex,...

Mono<String> resultAMono = loadA(); Mono<String> resultBMono = resultA.flatMap(resultA -> loadB());

这将链接并且 resultBMono 将在 resultAMono 返回时运行....

This will chain and resultBMono will run when resultAMono returns....

所以我的问题是,是否可以并行启动 2 个 Mono,并且当两个返回都继续使用另一个 Mono 时?

So my question is, is it possible to start 2 Mono's in parallel and when both returns continue with another Mono?

我认为它看起来像这样......

I think it will look something like this...

Mono<String> resultAMono = loadA(); Mono<String> resuktBMono = loadB(); Mono<Tuple2<Stirng, String> tupleMono = Mono.zip(resultAMono, resultBMono);

但我不知道这会并行运行,或者我可以做些什么来并行运行...

but I have no idea this will run in Parallel or what can I do this to run in parallel...

感谢回答....

推荐答案

2个语义,1个让它们并行运行的方法

我在下面介绍的两个选项都需要一些额外的调整才能使 A 和 B Mono 并行运行:即,每个 Mono 应该使用 subscribeOn(Scheduler) 从它们合并的地方脱离公共线程.

The two options I present below both need some additional tuning to make A and B Mono run in parallel: namely, each Mono should use subscribeOn(Scheduler) to get out of the common thread from where they're merged.

如果你只关心A和B的完成

使用 when 来监听 A 和 B 完成,then 继续使用完全不同的 Mono:

Use when to listen for A and B completion and then to continue with a completely different Mono:

Mono.when(monoAwithSubscribeOn, monoBwithSubscribeOn) .then(Mono.just("A and B finished, I don't know their value"));

如果您关心 A 和 B 值

根据您想要对结果做什么,使用 zip + map/flatMap.

Use zip + map/flatMap depending on what you want to do with the result.

Mono.zip(monoAwithSubscribeOn, monoBwithSubscribeOn) .map(tuple2 -> new Foo(tuple2.getT1(), tuple2.getT2(), "bar");

Mono.zip(monoAwithSubscribeOn, monoBwithSubscribeOn) .flatMap(tuple2 -> fetchMoreDataAsMono(tuple2.getT1(), tuple2.getT2()));

then 会忽略前面的数据,所以在它之前使用 zip 没有多大意义.

then will ignore the previous data, so it wouldn't make much sense to use zip before it.

此外,如果 A 或 B 之一为空,zip 将导致 空 Mono!使用 switchIfEmpty/defaultIfEmpty 来防止这种情况.

also, zip will result in an empty Mono if one of A or B is empty! Use switchIfEmpty/defaultIfEmpty to protect against that case.

更多推荐

是否可以并行启动 Mono 并汇总结果

本文发布于:2023-10-24 15:06:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Mono

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!