我们如何处理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);
参考:overload resolution https://github.com/square/retrofit/issues/690
答案 0 :(得分:9)
将 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);
});