我正在将Retrofit2与Rx一起使用。我有两个API调用。如果第一次调用返回的代码为400,则为空,我需要进行第二次API调用,否则,只是为了显示结果。我已经实现了自定义错误处理,如何显示here。这是我的解决方案:
getResponse1(token)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ObserverErrorImpl<Response1, BaseError>(BaseError.class) {
@Override
public void onNext(Response1 response) {
view.onSuccess(response);
}
@Override
public void onClientError(BaseError response) {
getResponse2(token)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ObserverErrorImpl<Response2, BaseError>(BaseError.class) {
@Override
public void onNext(Response2 response) {
view.onSuccess(response);
view.hideProgress();
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
view.hideProgress();
}
});
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
view.hideProgress();
}
});
是否可以简化方法
onClientError
中的代码?这样好解决吗? 最佳答案
1)。为简化起见,最好将Response1
和Response2
扩展一些基类,因此在您的链中,您可以使用基类进行操作,可以在需要时将其转换为特定类型。
因此,假设您拥有BaseResponse
:
public abstract class BaseResponse{
public static int TYPE_RESPONSE_1 = 1;
public static int TYPE_RESPONSE_2 = 2;
public abstract int getType(); //every class MUST override this method
}
Response1
和Response2
应该覆盖BaseResponse
2)。
getResponse1
和getResponse2
应该返回Observable<BaseResponse>
3)。您的目标代码:
getResponse1(token)
.onErrorResumeNext(new Func1<Throwable, Observable<BaseResponse>>() {
@Override
public Observable<BaseResponse> call(Throwable throwable) {
// I use Retrofit 1.9
// And in Retrofit 1.9 I have class RetrofitError, which may provide me all info about error
// I'm absolutelly sure Retrofit 2 also have such class,
// but it may have another name
if(/* is your target error */){
//cast it tour target error
return getResponse2(token);
}
return Observable.error(throwable);
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ObserverErrorImpl<Response1, BaseError>(BaseError.class) {
@Override
public void onNext(BaseResponse response) {
if(response.getType() == BaseResponse.TYPE_RESPONSE_1){
view.onSuccess(response);
} else {
view.onSuccess(response);
view.hideProgress();
}
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
view.hideProgress();
}
});