改进请求的通用基本方法

问题描述 投票:1回答:1

我有Retrofit和重复检查的问题。我必须每次检查response状态代码或类型!

我需要一个wrapper请求方法检查这里重复的工作。 (重复的作品包括:showLoading()response.code()onFailure()句柄......)。

我需要一个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();
            }
        });
java android design-patterns
1个回答
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();
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.