我有这个功能:
public static class CombinedResult<T, R> {
T t;
R r;
public CombinedResult(T t, R r) {
this.t = t;
this.r = r;
}
public T getObject1() {
return t;
}
public void setObject1(T t) {
this.t = t;
}
public R getObject2() {
return r;
}
public void setObject2(R r) {
this.r = r;
}
}
public static <A, B> Observable<CombinedResult<A, B>> combineObservablesParallel(Observable<A>
return Observable.zip(observable1, observable2, new BiFunction<A, B, CombinedResult<A, B>>() {
@Override
public CombinedResult<A, B> apply(A a, B b) throws Exception {
return new CombinedResult<>(a,b);
}
});
}
它结合了 2 observable并返回 1 Observable,它将两个observable的结果都放到CombinedResult
对象中,这里的问题是 { {1}} 函数组合了Paralllel上的observable。
我想要与zip
相同的东西,它按顺序执行observable并返回zip
或类似的结果。
可以解决什么问题?
答案 0 :(得分:3)
使用flatMap
上的observable1
运算符与observable2
和zip
运算符结合使用:
RxJava 1:
return observable1
.flatMap(new Func1<A, Observable<CombinedResult<A, B>>>() {
@Override
public Observable<CombinedResult<A, B>> call(A a) {
return Observable.just(a).zipWith(observable2, new Func2<A, B, CombinedResult<A, B>>() {
@Override
public CombinedResult<A, B> call(A a, B b) {
return new CombinedResult<>(a, b);
}
});
}
});
RxJava 2:
return observable1.flatMap(new Function<A, ObservableSource<CombinedResult<A,B>>>() {
@Override
public ObservableSource<CombinedResult<A,B>> apply(A a) throws Exception {
return Observable.just(a).zipWith(observable2, new BiFunction<A, B, CombinedResult<A, B>>() {
@Override
public CombinedResult<A, B> apply(A a, B b) throws Exception {
return new CombinedResult<>(a,b);
}
});
}
});
RxJava 2 Lambda:
return observable1.flatMap(a -> Observable.just(a).zipWith(observable2, CombinedResult::new));