如果我们不更改活动的状态或重新启动活动,是否会调用onChanged
方法?(即使数据发生变化(。如果它没有发生,我该如何让它发生?
onCreate() {
viewModel.getHolidaysDatesFromServer(..).observe(.....this,new Observer<GetHolidaysDatesFromServer>) {
onChanged(GetHolidaysDatesFromServer GetHolidaysDatesFromServer)
}
}
和我的视图模型类...
public class CalendarLifeCycleOwner extends AndroidViewModel {
Context context;
MutableLiveData<GetHolidaysDatesFromServer> MutableLiveDataGetHolidays=new MutableLiveData<>();
public CalendarLifeCycleOwner(@NonNull Application application) {
super(application);
this.context=application.getApplicationContext();
}
public MutableLiveData<GetHolidaysDatesFromServer> getHolidaysDatesFromServer(String upd_token,int product_id) {
JustProductId justProductId=new JustProductId();
justProductId.setProduct_id(product_id);
UserListInterface userListInterface= UserListService.createService(UserListInterface.class, Utility.ACCEPT_HEADER_V4);
Call<GetHolidaysDatesFromServer> getHolidaysDatesFromServerCall=userListInterface.GetProductHolidays(upd_token,justProductId);
getHolidaysDatesFromServerCall.enqueue(new Callback<GetHolidaysDatesFromServer>() {
@Override
public void onResponse(Call<GetHolidaysDatesFromServer> call, Response<GetHolidaysDatesFromServer> response) {
if (response.isSuccessful()) {
GetHolidaysDatesFromServer getHolidaysDatesFromServer=response.body();
MutableLiveDataGetHolidays.postValue(getHolidaysDatesFromServer);
}
}
@Override
public void onFailure(Call<GetHolidaysDatesFromServer> call, Throwable t) {
ErrorObject errorObject=new ErrorObject(t);
GetHolidaysDatesFromServer getHolidaysDatesFromServer=new GetHolidaysDatesFromServer();
getHolidaysDatesFromServer.setErrorObject(errorObject);
MutableLiveDataGetHolidays.setValue(getHolidaysDatesFromServer);
}
});
return MutableLiveDataGetHolidays;
}
}
但是在我只是更改数据后onChanged()
没有被调用......
谷歌实际上将这种(或非常熟悉的(问题描述为开发峰会上的反模式。建议的方法是使用类android.arch.lifecycle.Transformations
switchMap
。有关更多详细信息,请参阅文档页面。
尝试使用它并删除全局 MutableLiveData 变量
public MutableLiveData<GetHolidaysDatesFromServer> getHolidaysDatesFromServer(String upd_token,int product_id) {
MutableLiveData<GetHolidaysDatesFromServer> MutableLiveDataGetHolidays=new MutableLiveData<>();
//Your API call code goes here
return MutableLiveDataGetHolidays;
}