我对 Retrofit
和重复检查有疑问。
我必须在每次响应
状态代码或类型时检查!
我需要一个 wrapper
请求方法来检查这个重复的作品。
(重复作品包括:showLoading()
、response.code()
、onFailure()
handle...)。
为此我需要一个GenericMethod
:
UserService service = RetrofitInstance.getRetrofitInstance().create(UserService.class);
service.RequestVerification(token, mobileNumber).enqueue(new Callback<ClientData<User>>() {
@Override
public void onResponse(@NonNull Call<ClientData<User>> call, @NonNull Response<ClientData<User>> response) {
doAction();//Action must passed to this method.
GeneralTools.hideLoading();
}
@Override
public void onFailure(@NonNull Call<ClientData<User>> call, @NonNull Throwable t) {
GeneralTools.hideLoading();
dialogError.show();
}
});
最佳答案
试试下面
private static class CallbackHandler<T> implements Callback<T> {
@Override
public void onResponse(Call<T> call, Response<T> response) {
int code = response.code();
if (code >= 200 && code < 300) {
onSuccess(response);
} else if (code == 401) {
// logic to refresh token or user then recall the same api
call.clone().enqueue(this);
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
}
public void onSuccess(Response<T> response) {
}
}
然后像下面这样改变你的电话
service.RequestVerification(token, mobileNumber).enqueue(new CallbackHandler<ClientData<User>>() {
@Override
public void onSuccess(Response<ClientData<User>> response) {
doAction();//Action must passed to this method.
GeneralTools.hideLoading();
}
@Override
public void onFailure(@NonNull Call<ClientData<User>> call, @NonNull Throwable t) {
GeneralTools.hideLoading();
dialogError.show();
}
});
关于java - 根据要求改造通用基本方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52247339/