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?

+3


source to share


2 answers


You must use flatMap

:

obsOfA.flatMap(new Func1<A, Observable<B>>() {
    @Override
    public Observable<B> call(A a) {
        return obsOfB;
    }
})
.subscribe(/* obsOfB has completed */);

      



Every time it obsOfA

calls onNext(a)

, it call

will execute with this value a

.

+5


source


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.

+1


source







All Articles