繁体   English   中英

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

[英]How to stop main thread to complete all Mono calls?

我正在对 DB 进行多次单声道调用。并且需要所有 Mono 响应的结果来计算在声明的 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然后flatMap -it 使用提供的Mono 您在subscribe方法中的逻辑可以移动到Mono或包装Flux副作用运算符doOnNext中:

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

如果您的if后面的代码不需要在主线程中运行,那么最好保持反应性,因为@chrylis-cautiouslyoptimistic 已经建议。 使用reduce运算符将所有结果放在一起,生成当所有提供的单声道完成时完成的单声道:

Flux.fromIterable(SomeObject.getAccountLevelActiveList())
    .flatMap(account ->
        SubLineService.getLineLevelCustProfile(
            preNbsLineLevelConverter.getSubLine( account ))
    ).reduce(PollObject.getSubList(), (subList, subLine) ->
        sublist.put(accountLevelMtn.getMtn(), Optional.ofNullable(subLine))
    ).map(subList -> {
        // the code here will be executed first when all monos are completed
    })
    // ... other operators if necessary
    // eventually subscribing or returning the mono for further processing 
    .subscribe();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM