如何从Retrofit2调用OnResponse返回Java对象

时间:2018-07-14 15:55:06

标签: android json retrofit retrofit2 response

我有一个Restful API,谁为我返回了Java对象。当返回该对象时,它仍然为空,因为异步线程仍在工作。如何获得该响应并返回到Presenter,然后将正确的响应定向到视图?

那是我的改造电话:

 public String checkUser(final ModelUser modelUser) throws IOException {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(UserRetrofitAPI.BASE_SERVICE)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    UserRetrofitAPI userRetrofitAPI = retrofit.create(UserRetrofitAPI.class);
    Call<ModelUser> requestCheckUser = userRetrofitAPI.checkUser(modelUser.getUser(), modelUser.getPassword());
    requestCheckUser.enqueue(new Callback<ModelUser>() {
        @Override
        public void onResponse(Call<ModelUser> call, retrofit2.Response<ModelUser> response) {
            if(!response.isSuccessful()){

                myModelUser = new ModelUser(modelUser.getUser(),modelUser.getPassword(), String.valueOf(response.code()));

            } else {

                ModelUser modelUserChecked = response.body();
                myModelUser = modelUserChecked;
            }
        }

        @Override
        public void onFailure(Call<ModelUser> call, Throwable t) {

            Exception ex = new Exception(t);

            myModelUser = new ModelUser(modelUser.getUser(), modelUser.getPassword(), ex.toString());

        }
    });

    return myModelUser.getResponse();
}

当我执行此调试时,它会根据处理时间起作用。

帮我吗?

1 个答案:

答案 0 :(得分:1)

  

您不应该直接退货。

正如您提到的,改造响应在后台线程中更新。

我建议仅返回requestCheckUser,并在您的演示者

中进行观察
public Call<ModelUser> checkUser(final ModelUser modelUser) throws IOException {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(UserRetrofitAPI.BASE_SERVICE)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    UserRetrofitAPI userRetrofitAPI = retrofit.create(UserRetrofitAPI.class);
    Call<ModelUser> requestCheckUser = userRetrofitAPI.checkUser(modelUser.getUser(), modelUser.getPassword());

    return requestCheckUser;
}

观察演示者中对该呼叫的响应,并执行以下必需的操作

checkUser(modelUser).enqueue(new Callback<ModelUser>() {
    @Override
    public void onResponse(Call<ModelUser> call, retrofit2.Response<ModelUser> response) {
        if(!response.isSuccessful()){

            myModelUser = new ModelUser(modelUser.getUser(),modelUser.getPassword(), String.valueOf(response.code()));

        } else {

            ModelUser modelUserChecked = response.body();
            myModelUser = modelUserChecked;
        }
    }

    @Override
    public void onFailure(Call<ModelUser> call, Throwable t) {

        Exception ex = new Exception(t);

        myModelUser = new ModelUser(modelUser.getUser(), modelUser.getPassword(), ex.toString());

    }
});

这将是简单选项,并且将满足该用例和范围。 如果您不想在Presenter中编写观察者,则可以使用自定义接口侦听器

我建议研究 RxJava并将其与Retrofit一起使用,以将其转换为更易于维护的代码