英文:
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<List<String>> resultAMono = listA();
Mono<Void> resultBMono = loadB(resultAMono.block());
Mono<Void> 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
是因为loadB
和loadC
都返回Mono<Void>
,而我们不需要结果。
如果需要结果,可以使用Mono.zip
来并行解析发布者。
Mono<Tuple2<B, C>> res = resultAMono
.flatMap(a -> Mono.zip(loadB(a), loadC()));
Flux.merge
和Mono.zip
都会急切地订阅发布者。
英文:
You don't need to block
here. In reactive you need to build a flow combining different operators
Mono<Void> res = resultAMono
.flatMap(a -> Flux.merge(loadB(a), loadC()).then());
We are using Flux.merge
here because both loadB
& loadC
return Mono<Void>
and we don't need results.
In case results are needed Mono<B> loadB(A a)
& Mono<C> loadC()
we can use Mono.zip
to resolve publishers in parallel.
Mono<Tuple2<B, C>> res = resultAMono
.flatMap(a -> Mono.zip(loadB(a), loadC()));
Both Flux.merge
& Mono.zip
subscribes to publishers eagerly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论