我正在对 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 中。
如果你想停止主线程,那么你可以使用阻塞而不是订阅,但你必须首先使用provided将其转换List
为inFlux
和flatMap
-it Mono
。您在subscribe
方法中的逻辑可以移动到或 wrapping 的副作用运算符doOnNext
中:Mono
Flux
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句