当将 Observables 与 Retrofit 结合使用时,如何处理网络故障?
鉴于此代码:
Observable<GetJobResponse> observable = api.getApiService().getMyData();
observable
.doOnNext(new Action1<GetJobResponse>() {
@Override
public void call(GetJobResponse getJobResponse) {
//do stuff with my data
}
})
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
//do stuff with error message
}
});
如果没有网络,请求就会失败,并且 onError 不会被调用。它不会崩溃,而是默默地失败。日志显示 Retrofit 出现错误:
java.net.UnknownHostException: Unable to resolve host "api-staging.sittercity.com": No address associated with hostname
at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.squareup.okhttp.internal.Dns$1.getAllByName(Dns.java:29)
使用回调,这可以简单地传递给 onFailure(RetrofitError error)。我怎样才能用 RxJava 来实现这一点?
我的问题实际上是在我的代码的其他地方。使用 rxJava + Retrofit 处理网络错误非常简单,因为它只是在 onError 方法中抛出一个 RetrofitError :
@Override
public void onError(Throwable e) {
if (e instanceof RetrofitError) {
if (((RetrofitError) e).isNetworkError()) {
//handle network error
} else {
//handle error message from server
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)