如何停止主线程来完成所有Mono调用?

问题描述

我正在对数据库进行多个单声道调用,并且需要所有单声道响应的结果来计算最终结果,该最终结果将在声明的单声道逻辑之后写入。

if (SomeObject.getAccountLevelActiveList() != null) {

                SomeObject.getAccountLevelActiveList().parallelStream().forEach(account -> {
                    Mono<SubLine> subLineMono= SubLineService
                            .getLineLevelCustProfile(preNbsLineLevelConverter.getSubLine(account ));
                

                    subLineMono.subscribe(subLine-> PollObject.getSubList()
                            .put(accountLevelMtn.getMtn(),Optional.ofNullable(subLine)));

                });

            }

但是在将单声道结果​​存储到 PollObject 之前,我的主要逻辑正在执行。因此我在 PollObject 中得到的是null。因此,我想停止主线程,直到将Mono结果存储到 PollObject

解决方法

如果要停止主线程,则可以使用阻塞而不是订阅,但是必须首先将List转换为Flux,然后再使用提供的{{1 }}。您可以将flatMap方法中拥有的逻辑移到Mono或包装subscribe的副作用运算符doOnNext中:

Mono

如果不需要Flux之后的代码在主线程中运行,则最好保持反应性,因为已经建议了@ chrylis-cautiouslyoptimistic。使用Flux.fromIterable(SomeObject.getAccountLevelActiveList()) .flatMap(account -> SubLineService.getLineLevelCustProfile( preNbsLineLevelConverter.getSubLine( account )) ).doOnNext(subLine -> PollObject.getSubList().put(accountLevelMtn.getMtn(),Optional.ofNullable(subLine)) ).blockLast(); // the following code will be executed first when all monos are completed 运算符将所有结果放在一起,以产生在提供的所有Monos完成时完成的mono:

if

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...