How can I execute two independent Observables sequentially without nesting calls?
Using RxJava I have Observable<A>
and Observable<B>
. I want to start a subscription B
as soon as the first (and only) item comes out A
. I know that I can link it like this:
final Observable<A> obsOfA;
final Observable<B> obsOfB;
obsOfA.subscribe(new Action1<A>() {
@Override
public void call(A a) {
obsOfB.subscribe(...)
}
});
.. But this will lead to nesting syntax, which becomes ugly as soon as we imagine Observable<C>
. How can I "expand" the syntax faster - get one that looks more like javascript- Promise.then()
flow?
source to share
You can use switch
in conjunction with map
in switchMap
:
obsOfA.switchMap(i -> obsOfB)
.subscribe(/* obsOfB has completed */);
This is almost the same as merge
in flatMap
, so far obsOfA
it only gives a value of 1, but when it gives more values, it flatMap
will combine them and switch
only subscribe to the last instance obsOfB
. This can be useful when you need to switch to a different stream.
source to share