Reputation: 135
I have been trying to learn Project Reactor 3.0 with this small application. I am struggling to compose a Flux.zip() function for combining variables to a Movie object. In Reactor it seems like the return type is a Flux<Tuple5<>>
. In RxJava2 it returns a Function5<>
.
RxJava2
Single<Movie> movie = Single.zip(getDesc(id), getCategory(id), getName(id), getRating(id),
(Function5<Integer, String, String, String, Double, Object>) (desc, cat, name, rating) ->
new Movie(id.blockingGet(), name, desc, cat, rating)).cast(Movie.class);
Reactor
Flux<Tuple5<Integer, String, String, String, Double>> tuple =
Flux.zip(id, getDesc(id), getCategory(id), getName(id), getRating(id));
Instead of returning a Flux<Tuple5<>>
I want to return a Tuple5<>
or something else to create the movie just like RxJava. I do not want to subscribe to the Tuple since I am trying to return this in Spring Web Reactive. I temporarily solved it by subscribing, but I was wondering if it is possible to do the same as RxJava.
The example in this video on timestamp 1:07:54, shows it was possible in an old version.
Any solutions or suggestions are welcome!
Upvotes: 2
Views: 14321
Reputation: 837
Yes,Zip
can be used. It waits for sources to emit an element and combine them in Tuples. Like below publishers are emitting first name, last name and dept. which is being combined to form User flux.
Flux<String> fnameFlux = Flux.just("Ramesh","Amit","Vijay");
Flux<String> lnameFlux = Flux.just("Sharma","Kumar","Lamba");
Flux<String> deptFlux = Flux.just("Admin","IT","Acc.");
Flux<User> userFlux = Flux.zip(fnameFlux, lnameFlux, deptFlux)
.flatMap(dFlux ->
Flux.just(new User(dFlux.getT1(), dFlux.getT2(), dFlux.getT2())));
userFlux.subscribe(x -> System.out.println(x));
Upvotes: 1
Reputation: 28301
The RxJava solution doesn't return the Movie
directly, but a Single<Movie>
. Reactor has a simplified zip
that returns a Tuple
, but that RxJava signature is comparable to Flux<Tuple5>
.
So what you want is a Flux<Movie>
. zip
has an overload that takes a Function<Object[], V>
as the first parameter: that lets you specify into which object V
the values from the zipped sources are to be combined. The function will be applied with an array of these values as input, and must return the value to be emitted in the resulting Flux<V>
, in your case a Movie
.
Upvotes: 2