我们如何处理 Rxjava2 中的不同网络错误?
我们曾经使用 Rxjava 1 检查 throwable 的实例,如果它是 IOException 或 HttpException 返回,但是在 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);
参考:https ://github.com/square/retrofit/issues/690 https://android.googlesource.com/platform/libcore/+/5d930ca/luni/src/main/java/android/system/GaiException.java