问题
I'm zipping multiple Observables together and then transforming them in a way that results in an Observable:
final Observable<Observable<M>> result = Observable.zip(obs1, obs2, transformFunc);
What I'd like to be able to do is:
final Observable<M> result = Observable.flatZip(obs1, obs2, transformFunc);
What's the cleanest way to do this, given flatZip doesn't exist (maybe I should submit one). At the moment I'm having to flatMap the result in on itself.
回答1:
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));
}
}
回答2:
What 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'll need one for each number of arguments, but that's how it goes with zip, too. Guessing that is not the pain point here.
回答3:
Here is what I've ended up using 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));
}
回答4:
Well the simplest thing to do would be as follows
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
来源:https://stackoverflow.com/questions/23721701/flatzip-in-rxjava