Reputation: 46
I have two observables apiService.getFeed()
& apiService.getProfile()
I want to load both data in same screen & inorder to do that and handle errors I need to call apiService.getProfile()
after apiService.getFeed()
.
I have looked up a lot of examples but most of it seem to use flatMap & am not sure if we can use it especially because the two observable are of different class types and both are independent in terms of values.
Upvotes: 0
Views: 465
Reputation: 1
Return your retrofit responses as Observable, then use the zip operator. http://reactivex.io/documentation/operators/zip.html
When one api call has dependency on the other api call, zip operator is the ideal since the Zip operator combines the emission of two observables in order.
Observable <String> feed = apiService.getFeed("param");
Observable <String> profile = apiService.getProfile("param");
Observable.zip(
feed, profile,
new Func2<String, String, ResultType>() {
@Override
public ResultType call(String feedResponse,
String profileResponse) {
// Do something with the feedResponse
// Do something with the profileResponse
// Return something with ResultType
return something;
}
}).subscribe(
//Once requests process are done
new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
//on successful completion of the request
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable e) throws Exception {
//on error
}
});
Upvotes: 0
Reputation: 23
This is how I would nest two Retrofit
calls with RxJava2
's flatMap
:
apiService.getFeed(param1, param2, ...)
.flatMap(result -> apiService.getProfile(param1, param2, ...))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
//do something here
}, throwable -> {
view.showErrorMessage(throwable.getMessage());
});
But if it's two different observable types, you can also use different variants of flatMap:
flatMap
- returns a Single
flatMapCompletable
- returns a Completable
flatMapMaybe
- returns a Maybe
flatMapObservable
- returns an Observable
flatMapPublisher
- returns a Flowable
Upvotes: 1