Reputation: 18603
Using RxJava I have an Observable<A>
and an Observable<B>
. I want to start subscription on B
as soon as the first (and only) element of A
is emitted. I know I can chain 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 cause a nesting syntax which gets ugly as soon as we introduce Observable<C>
. How can I "unwrap" the syntax to a more fluent one - getting one that is more like the javascript Promise.then()
-flow?
Upvotes: 3
Views: 207
Reputation: 15054
You should use flatMap
:
obsOfA.flatMap(new Func1<A, Observable<B>>() {
@Override
public Observable<B> call(A a) {
return obsOfB;
}
})
.subscribe(/* obsOfB has completed */);
Every time obsOfA
calls onNext(a)
, call
will be executed with this value a
.
Upvotes: 5
Reputation: 7546
You can use switch
, combined with map
in switchMap
:
obsOfA.switchMap(i -> obsOfB)
.subscribe(/* obsOfB has completed */);
This does almost the same as merge
in flatMap
as long as obsOfA
only yield 1 value, but when it yield more values, flatmap
will combine them, while switch
will only be subscribed to the last instance of obsOfB
. This might be useful when you need to switch to a different stream.
Upvotes: 1