将 List<Mono<String>> 转换为 Flux<String>
Convert List<Mono<String>> to Flux<String>
问题很少,但答案对某些代码非常具体。
一般如何将Mono的Stream转为Flux
List<Mono<String> listOfMono = stream()
.map( s -> { do something and return Mono<String> } )
.collect(Collectors.toList());
如何将 listOfMono
对象转换为 Flux<String>
您可以使用 fromIterable and then use flatMap 来展平 Mono
Transform the elements emitted by this Flux asynchronously into Publishers, then flatten these inner publishers into a single Flux through merging, which allow them to interleave.
Flux<String> result = Flux.fromIterable(listOfMono)
.flatMap(Function.identity());
如果您输入的是 Monos 列表,您可以简单地执行以下操作:
Flux.merge(listOfMono);
如果你的输入是流,你可以做
stream()
.map( s -> { do something and return Mono<String> } )
.collect(Collectors.collectingAndThen(Collectors.toList(), Flux::merge));
或
Flux.fromStream(stream())
.flatMap( s -> { do something and return Mono<String> } )
我个人更喜欢最后一个选项,因为这是最直接和惯用的。
问题很少,但答案对某些代码非常具体。
一般如何将Mono的Stream转为Flux
List<Mono<String> listOfMono = stream()
.map( s -> { do something and return Mono<String> } )
.collect(Collectors.toList());
如何将 listOfMono
对象转换为 Flux<String>
您可以使用 fromIterable and then use flatMap 来展平 Mono
Transform the elements emitted by this Flux asynchronously into Publishers, then flatten these inner publishers into a single Flux through merging, which allow them to interleave.
Flux<String> result = Flux.fromIterable(listOfMono)
.flatMap(Function.identity());
如果您输入的是 Monos 列表,您可以简单地执行以下操作:
Flux.merge(listOfMono);
如果你的输入是流,你可以做
stream()
.map( s -> { do something and return Mono<String> } )
.collect(Collectors.collectingAndThen(Collectors.toList(), Flux::merge));
或
Flux.fromStream(stream())
.flatMap( s -> { do something and return Mono<String> } )
我个人更喜欢最后一个选项,因为这是最直接和惯用的。