How can we handle different network errors in Rxjava2 ?
We used to check the instance of the throwable if it's of IOException or HttpException back with Rxjava 1 ,however, in RxJava 2 the throwable error is of type GaiException.
code snippet
RestAPI restAPI = RetrofitHelper.createRetrofitWithGson().create(RestAPI.class);
Observable<BaseResponseTourPhoto> observable = restAPI.fetchData("Bearer " + getAccessToken(), "2", "" + page)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
Disposable subscription = observable.subscribe(BaseResponse-> {
onLoadingFinish(isPageLoading, isRefreshing);
onLoadingSuccess(isPageLoading, BaseResponse);
writeToRealm(BaseResponse.getData());
}, error -> {
onLoadingFinish(isPageLoading, isRefreshing);
onLoadingFailed(error);
});
mCompositeDisposable = new CompositeDisposable();
mCompositeDisposable.add(subscription);
unsubscribeOnDestroy(mCompositeDisposable);
reference: https://github.com/square/retrofit/issues/690 https://android.googlesource.com/platform/libcore/+/5d930ca/luni/src/main/java/android/system/GaiException.java
Rx gives you a very granular control over which threads will be used to perform work in various points within a stream. To point the contrast here already, basic call approach used in Retrofit is only scheduling work on its worker threads and forwarding the result back into the calling thread.
To use RxJava in retrofit environment we need to do just two major changes: Add the RxJava in Retrofit Builder. Use Observable type in the interface instead of Call.
Retrofit is a HTTP Client for Android and Java developed by Square. We are going to integrate Retrofit with RxJava to simplify threading in our app. In addition, we will also integrate RxAndroid to make network calls.
Add onErrorReturn() to the chain
.onErrorReturn((Throwable ex) -> {
print(ex); //examine error here
return ""; //empty object of the datatype
})
.subscribe((String res) -> {
if(res.isEmpty()) //some condition to check error
return;
doStuff(res);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With