处理Rxjava 2中的网络错误 - 改造2

mhd*_*ban 8 rx-java okhttp retrofit2 okhttp3 rx-java2

我们如何处理Rxjava2中的不同网络错误?

我们曾经检查过throwable的实例,如果它是IOException或HttpException返回Rxjava 1,但是,在RxJava 2中,throwable错误是GaiException类型.

代码段

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);
Run Code Online (Sandbox Code Playgroud)

参考:https ://github.com/square/retrofit/issues/690 https://android.googlesource.com/platform/libcore/+/5d930ca/luni/src/main/java/android/system/GaiException.java

Eki*_*ano 10

onErrorReturn()添加到链中

.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);
});
Run Code Online (Sandbox Code Playgroud)