我正在使用 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) 我正在使用 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)