【问题标题】:Retrofit Generic Base Method for request改造通用基本方法的请求
【发布时间】:2018-09-09 18:12:51
【问题描述】:

我对@9​​87654322@ 和重复检查有疑问。 我每次都要检查response状态码或输入!

我需要一个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();
            }
        });

【问题讨论】:

  • 重复作品??请简化您的要求
  • 我需要检查 response.code() 如果是 401 处理用户再次登录。我必须在所有请求 OnResponse() 中每次都检查它?!我需要在基本方法或其他东西中检查一次。 @KrishnaSharma
  • stackoverflow.com/questions/37302889/… 这将是您的解决方案

标签: java android design-patterns


【解决方案1】:

试试下面

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();
    }
});

【讨论】:

  • 感谢 Krishna,在第 2 步改造 2.0 服务方法不能返回 void,你对改造 2 的解决方案是什么?
  • @AmirNorouzpour 这不是实际的服务/改造接口方法调用,它是客户端的包装方法,它将在内部调用实际的服务/改造接口方法调用。 查看更新后的答案
  • requestVerification(第 2 步)我应该在哪里定义?!
  • 第 2 步和第 5 步应该在 UI 级别,例如活动或片段
  • 这是正确的做法,不用担心已根据您的需要更新了答案。
猜你喜欢
  • 2019-06-14
  • 2021-05-19
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 2014-02-17
  • 2020-01-13
  • 2016-12-08
相关资源
最近更新 更多