FlatZip in RxJava

I compress several Observables together and then transform them in such a way that results in an observation:

final Observable<Observable<M>> result = Observable.zip(obs1, obs2, transformFunc); 

What I would like to do is:

 final Observable<M> result = Observable.flatZip(obs1, obs2, transformFunc); 

What is the cleanest way to do this if flatZip doesn't exist (maybe I should introduce it). Right now I need to execute the flatMap result on my own.

+6
source share
4 answers
 public class RxHelper { public static <T1, T2, R> Observable<R> flatZip(Observable<? extends T1> o1, Observable<? extends T2> o2, final Func2<? super T1, ? super T2, Observable<? extends R>> zipFunction) { return Observable.merge(Observable.zip(o1, o2, zipFunction)); } public static <T1, T2, T3, R> Observable<R> flatZip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, Observable<? extends R>> zipFunction) { return Observable.merge(Observable.zip(o1, o2, o3, zipFunction)); } public static <T1, T2, T3, T4, R> Observable<R> flatZip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Func4<? super T1, ? super T2, ? super T3, ? super T4, Observable<? extends R>> zipFunction) { return Observable.merge(Observable.zip(o1, o2, o3, o4, zipFunction)); } } 
+8
source

How about this:

 public static <A,B,C> Observable<C> flatZip(Observable<A> o1, Observable<B> o2, F2<A,B,Observable<C>> transformer) { Observable<Observable<C>> obob = Observable.zip(o1, o2, (a, b) -> { return transformer.f(a, b); }); Observable<C> ob = obob.flatMap(x -> x); return ob; } 

Of course, you will need one for each number of arguments, but the same way as with zip. Guess it's not pain here.

+3
source

Here is what I used in my project:

 /** * Zips results of two observables into the other observable. * Works like zip operator, except zip function must return an Observable */ public static <T, V, R> Observable<R> flatZip(Observable<T> o1, Observable<V> o2, Func2<? super T, ? super V, Observable<R>> zipFunction) { return Observable.zip(o1, o2, Pair::new).flatMap(r -> zipFunction.call(r.first, r.second)); } 
0
source

Well, the easiest way would be to do the following:

 final Observable<M> result = Observable.zip(obs1, obs2, (o1, o2) -> { return new M(o1, o2); // construct a new M and return it from here. }); 

Hope this helps

anand raman

-1
source

Source: https://habr.com/ru/post/969466/


All Articles