怎么把List <mono <t >>转换成Mono <list <t >>?

时间:2018-11-09 18:35:53

标签: java project-reactor reactor

我有一个返回Mono<Output>的方法:

interface Processor {
  Mono<Output> process(Input input);
}

我想对集合执行此processor方法:

List<Input> inputs = // get inputs
Processor processor = // get processor
List<Mono<Output>> outputs = inputs.stream().map(supplier::supply).collect(toList());

但是我要获得一个包含汇总结果的List<Mono<Output>>,而不是Mono<List<Output>>

我尝试了reduce,但最终结果看起来很笨拙:

Mono<List<Output>> result = inputs.stream().map(processor::process)
    .reduce(Mono.just(new ArrayList<>()),
        (monoListOfOutput, monoOfOutput) ->
            monoListOfOutput.flatMap(list -> monoOfOutput.map(output -> {
              list.add(output);
              return list;
            })),
        (left, right) ->
            left.flatMap(leftList -> right.map(rightList -> {
              leftList.addAll(rightList);
              return leftList;
            })));

我可以用更少的代码来实现吗?

2 个答案:

答案 0 :(得分:4)

如果您不必出于任何原因创建流,则可以从输入中创建Flux,对其进行映射并收集列表

Flux.fromIterable(inputs).flatMap(processor::process).collectList();

答案 1 :(得分:1)

// first merge all the `Mono`s:
List<Mono<Output>> outputs = ...
Flux<Output> merged = Flux.empty();
for (Mono<Output> out : outputs) {
    merged = merged.mergeWith(out);
}

// then collect them
return merged.collectList();

或(受亚历山大的回答启发)

Flux.fromIterable(outputs).flatMap(x -> x).collectList();