project reactor - 如何结合 Mono 和 Flux?
project reactor - How to combine a Mono and a Flux?
我有一个 Flux 和 Mono,但我不确定如何将它们组合起来,以便我在 Flux 的每个项目中都具有单声道值。
我正在尝试这种方法,但它不起作用:
Mono<String> mono1 = Mono.just("x");
Flux<String> flux1 = Flux.just("{1}", "{2}", "{3}", "{4}");
Flux.zip(mono1, flux1, (itemMono1, itemFlux1) -> "-[" + itemFlux1 + itemMono1 + "]-").subscribe(System.out::println);
The outcome that I'm getting is -[{1}x]-
How could I combine them in order to get -[{1}x, {2}x, {3}x, {4}x]-?
Zip 查找对以将它们加在一起,您的逻辑看起来会更改通量值。
Mono<String> mono1 = Mono.just("x");
Flux<String> flux1 = Flux.just("{1}", "{2}", "{3}", "{4}");
flux1.flatMap(x -> mono1.map(m -> x+m)).subscribe(System.out::println);
在某些情况下,它比连接字符串更复杂,因此您必须依赖元组。
Flux<Object> myFlux = Flux.just(1,2,3,4);
Mono<Object> myMono = Mono.just("hello");
// combined flux with mono
myFlux.flatMap(fluxItem ->
myMono.map(monoItem -> Tuples.of(fluxItem, monoItem)))
// this will have pairs of ( (1, "hello"), (2, "hello"), (3, "hello"), (4, "hello") )
虽然 Kevin Hussey 的解决方案是正确的,但我认为换一种方式更好:
Mono<String> mono1 = Mono.just("x");
Flux<String> flux1 = Flux.just("{1}", "{2}", "{3}", "{4}");
mono1.flatMapMany(m -> flux1.map(x -> Tuples.of(x, m))).subscribe(System.out::println);
这样您就可以订阅 mono1
,而不是为 flux1
的每个值创建一个。请参阅 Flux.flatMap()
方法文档中的弹珠图。
按照 Alan Sereb 的建议,我正在使用元组。
我有一个 Flux 和 Mono,但我不确定如何将它们组合起来,以便我在 Flux 的每个项目中都具有单声道值。
我正在尝试这种方法,但它不起作用:
Mono<String> mono1 = Mono.just("x");
Flux<String> flux1 = Flux.just("{1}", "{2}", "{3}", "{4}");
Flux.zip(mono1, flux1, (itemMono1, itemFlux1) -> "-[" + itemFlux1 + itemMono1 + "]-").subscribe(System.out::println);
The outcome that I'm getting is -[{1}x]-
How could I combine them in order to get -[{1}x, {2}x, {3}x, {4}x]-?
Zip 查找对以将它们加在一起,您的逻辑看起来会更改通量值。
Mono<String> mono1 = Mono.just("x");
Flux<String> flux1 = Flux.just("{1}", "{2}", "{3}", "{4}");
flux1.flatMap(x -> mono1.map(m -> x+m)).subscribe(System.out::println);
在某些情况下,它比连接字符串更复杂,因此您必须依赖元组。
Flux<Object> myFlux = Flux.just(1,2,3,4);
Mono<Object> myMono = Mono.just("hello");
// combined flux with mono
myFlux.flatMap(fluxItem ->
myMono.map(monoItem -> Tuples.of(fluxItem, monoItem)))
// this will have pairs of ( (1, "hello"), (2, "hello"), (3, "hello"), (4, "hello") )
虽然 Kevin Hussey 的解决方案是正确的,但我认为换一种方式更好:
Mono<String> mono1 = Mono.just("x");
Flux<String> flux1 = Flux.just("{1}", "{2}", "{3}", "{4}");
mono1.flatMapMany(m -> flux1.map(x -> Tuples.of(x, m))).subscribe(System.out::println);
这样您就可以订阅 mono1
,而不是为 flux1
的每个值创建一个。请参阅 Flux.flatMap()
方法文档中的弹珠图。
按照 Alan Sereb 的建议,我正在使用元组。