java - 根据要求改造通用基本方法

标签 java android design-patterns

我对 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/

相关文章:

java - 使用 APACHE Shiro 将用户重定向到特定 URL

android - 将 OnFling 和 OnClick 方法添加到 ImageView

design-patterns - 日志代码应该去哪/什么级别?

java - 如何将 html 页面(JSP)中选定的信息发送到 servlet?

java - SolrJ 无效的内容类型

java - IE11 上的 Selenium WebDriver 在 URL 中总是有 "--port="

Android:使用 MoPub 中介但 Admob 报告展示次数为 0?

android - 适用于 Android 2.2 但不适用于 Android 2.3

ios - iOS 中的设计模式作为装饰器模式

c# - 在内部(在同一程序集中)将项目添加到 ReadOnlyCollection<T> 的最佳方法?