Reputation: 607
I'm quite new to Rx and I have a situation that I don't find anything about (or maybe I don't ask the right question). I have an observable that should trigger a specific method. However to call that method I need the value from a second observable (which will btw have that value always before the first one). How do I combine the two so that the method only gets called when the first observable fires? It's like with combineLatest, but that one fires if either of the Observables fire. Br, Daniel
Upvotes: 0
Views: 3498
Reputation: 217
You can use Flatmap() to do the same if you are using java 8 then :
Observable.just(function1()).flatMap( dataFromFirstObservable->
Observable.just(function2(dataFromFirstObservable))
).subscribe(resultFromSecondObservable -> {
//perform action here
});
if using java 7
Observable.just(getData1()).flatMap(new Function<Integer, ObservableSource<?>>() {
@Override
public ObservableSource<?> apply(Integer integer) throws Exception {
return Observable.just(function2(integer));
}
}).subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
//perform action here
}
});
Upvotes: 0
Reputation: 7486
It's quite simple. You just have to call another observable once the first observable is complete or in case the second observable relies on the successive data reception from the first observable, you need to call the second observable in onNext().
The following code tries to illustrate how the observable code would end up looking. I haven't checked the mistakes in syntax etc so use the following code to formulate an idea.
Observable.just(getDataFromServer())
.subscribeWith(new DisposableObserver() {
ArrayList<MyData> dataList = new ArrayList<>();
public void onNext(MyData d) {
// call second observable here if it relies on batches of data the first observable has
dataList.add(d);
}
public void onComplete() {
Observable.from(dataList).map(new Func1<MyData, String>() {
@Override public String call(MyData data) {
// apply your operations etc
}
});
}
});
Upvotes: 0
Reputation: 959
If I understand the question correctly you can use the withLatestFrom
operator so that the combination and subsequent emission is gated by the first observable.
It is listed on the same page with combine latest: http://reactivex.io/documentation/operators/combinelatest.html
Upvotes: 1