小编Ash*_*ora的帖子

通过 mvvm android 进行异常处理

我正在使用 MVVM 架构通过在 android studio 中进行改造来访问 Web 服务。我已经在我的视图类中处理了服务的响应。但我面临的问题是如何处理异常并将它们传递给我的视图类。一种方法是在我的 Bean 类中创建构造函数并将响应和错误传递给它并更新 UI。但我想要更优化的方式来处理 UI 内的异常。

这是我的存储库代码:

final MutableLiveData<MyBeanClass> myBeanClass = new MutableLiveData<>();
   ApiInterface apiInterface = ApiClient.getClientAuthentication().create(ApiInterface.class);
    Call<MyBeanClass> call = apiInterface.getData(id);
    call.enqueue(new Callback<MyBeanClass>() {
        @Override
        public void onResponse(Call<MyBeanClass> call, Response<MyBeanClass> response) {
            if(response.body()!=null) {
                myBeanClass.setValue(response.body());
            }
        }

        @Override
        public void onFailure(Call<MyBeanClass> call, Throwable t) {
         //How to handle exceptions here and pass the exception to UI without making constructor in bean class
        }
    });

    return myBeanClass;
Run Code Online (Sandbox Code Playgroud)

android exception-handling mvvm retrofit

3
推荐指数
2
解决办法
6315
查看次数

如何处理 mvvm android 中的异常并将该异常传递给我们的视图

我正在使用 MVVM 架构通过在 android studio 中进行改造来访问 Web 服务。我已经在我的视图类中处理了服务的响应。但我面临的问题是如何处理异常并将它们传递给我的视图类。一种方法是在我的 Bean 类中创建构造函数并将响应和错误传递给它并更新 UI。但我想要更优化的方式来处理 UI 内的异常。

这是我的存储库代码:

final MutableLiveData<MyBeanClass> myBeanClass = new MutableLiveData<>();ApiInterface apiInterface = ApiClient.getClientAuthentication().create(ApiInterface.class);
Call<MyBeanClass> call = apiInterface.getData(id);
call.enqueue(new Callback<MyBeanClass>() {@Override
    public void onResponse(Call<MyBeanClass> call, Response<MyBeanClass> response) {
        if(response.body()!=null) {
            myBeanClass.setValue(response.body());
        }
    }

    @Override
    public void onFailure(Call<MyBeanClass> call, Throwable t) {
     //How to handle exceptions here and pass the exception to UI without making constructor in bean class
    }
});

return myBeanClass;
Run Code Online (Sandbox Code Playgroud)

android exception-handling mvvm viewmodel retrofit2

3
推荐指数
1
解决办法
2744
查看次数