web-dev-qa-db-ja.com

Rxjava2でのネットワークエラーの処理-レトロフィット2

Rxjava2でさまざまなネットワークエラーを処理するにはどうすればよいですか?

以前は、スローアブルのインスタンスがIOExceptionまたはHttpExceptionであるかどうかをRxjava 1でチェックしていましたが、RxJava 2では、スローアブルエラーのタイプは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/69https://Android.googlesource.com/platform/libcore/+/5d930ca/luni/src/ main/Java/Android/system/GaiException.Java

8
mhdtouban

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);
});
9
Ekim Kano