Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Network Error in Rxjava 2 - Retrofit 2

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

like image 772
mhdtouban Avatar asked Dec 29 '16 12:12

mhdtouban


People also ask

What is the difference between RxJava and retrofit?

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.

How do you use RxJava with retrofit?

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.

What is retrofit RxJava?

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.


1 Answers

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);
});
like image 104
Ekim Kano Avatar answered Oct 25 '22 06:10

Ekim Kano