Reputation: 16639
I have this function:
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);
}
});
}
It combine 2 observables and return 1 Observable, which will get the result of both observables into CombinedResult
object, The problem here is zip
function combine the observables on Paralllel.
I want something same as zip
that executes the observable sequentially and return the result in BiFunction
or something like this.
what can be the solution ?
Upvotes: 3
Views: 3357
Reputation: 20268
Use flatMap
operator on observable1
combined with observable2
and zip
operator:
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));
Upvotes: 4