I started using Retrofit and RxJava recently and I love it. I am working on an Android project and I am following MVP Repository pattern as specified in Android Architecture Components. I'm still learning though.
Whenever I have to make an API call, I do it like this in the Presenter:
fruitsRepository
.getFeaturedFruits()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<UniversalResponse<Fruit>>() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
@Override
public void onNext(UniversalResponse<Fruit> universalResponse) {
if (view.isLost()) return;
view.setProgressVisibility(false);
if (universalResponse.isSessionExpired()) {
view.onSessionExpired();
return;
}
if (universalResponse.isError()) {
if (universalResponse.isServerError()) {
view.showErrorViewerPage(universalResponse.getServerErrorMessage());
}
view.showFeaturedFruitsError(universalResponse.getMessage());
return;
}
List<Fruit> fruits = universalResponse.getItems();
if (fruits != null && fruits.size() > 0) {
view.showFeaturedFruits(fruits);
}
else {
view.showNoFeaturedFruits();
}
}
@Override
public void onError(Throwable e) {
if (view.isLost()) return;
view.setProgressVisibility(false);
view.showFeaturedFruitsError(e.getMessage());
}
@Override
public void onComplete() {
if (view.isLost()) return;
view.setProgressVisibility(false);
}
});
fruitsRepository
is a Repository that can get data from local or remote source..getFeaturedFruits()
calls retrofit internally if remote source is selectedcompositeDisposable
isCompositeDisposable
UniversalResponse
is a class havinghttpStatusCode
,isSuccess
andList<T>
view
is an implementation of UI fromFeaturedFruitsContract.View
I am looking for some improvements to this. Can I reduce this somehow? If I have to make 5 different API calls, my presenter gets really bigger and repetitive. I was thinking about making an adapter for Observer I am using to subscribe.