在RxJava中展平

时间:2014-05-18 12:07:16

标签: java asynchronous observable rx-java

我将多个Observable压缩在一起,然后以导致Observable的方式对它们进行转换:

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

我希望能够做到的是:

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

这是最干净的方法,因为flatZip不存在(也许我应该提交一个)。目前我不得不将结果平面映射到自身。

4 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:3)

这个怎么样:

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

当然,每个参数的数量都需要一个,但这也是zip的结果。猜测这不是痛点。

答案 2 :(得分:0)

以下是我最终在项目中使用的内容:

/**
 * 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));
}

答案 3 :(得分:-1)

最简单的事情如下

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

希望这有帮助

anand raman