8

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

RxJava 1 では、スロー可能なエラーのインスタンスが IOException または HttpException であるかどうかをチェックしていましたが、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/690 https://android.googlesource.com/platform/libcore/+/5d930ca/luni/src/main/java/android/system/GaiException.java

4

1 に答える 1