Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

project reactor - How to combine a Mono and a Flux?

I have a Flux and Mono and I'm not sure how to combine them so that I will have the mono value in each item of the Flux.

I'm trying this approach but it's not working:

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]-?
like image 576
Giulia Colaço Avatar asked Jul 30 '18 22:07

Giulia Colaço


1 Answers

While Kevin Hussey's solution is a correct one, I think it is better to have it another way around:

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);

This way you have 1 subscription to mono1, instead of creating one for each value of flux1. See the marble diagram in the documentation for Flux.flatMap() method.

As suggested by Alan Sereb, I am using tuples.

like image 141
Konstantin Kolinko Avatar answered Nov 14 '22 12:11

Konstantin Kolinko