问题
Will the onChanged
method be called if we dont change the state of the activity or restart the activity? ( Even if the data changes ) . If it doesnt happen how shall i make it happen ?
onCreate() {
viewModel.getHolidaysDatesFromServer(..).observe(.....this,new Observer<GetHolidaysDatesFromServer>) {
onChanged(GetHolidaysDatesFromServer GetHolidaysDatesFromServer)
}
}
and my ViewModel class ...
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;
}
}
But after i just change the data onChanged()
is not getting called ...
回答1:
Google actually described that (or very familiar to that) kind of issue as an anti-pattern on the dev-summit.
The recommended approach is to use switchMap
from android.arch.lifecycle.Transformations
class.
You can see the documentation page for more details.
回答2:
Try using this and delete the global MutableLiveData variable
public MutableLiveData<GetHolidaysDatesFromServer> getHolidaysDatesFromServer(String upd_token,int product_id) {
MutableLiveData<GetHolidaysDatesFromServer> MutableLiveDataGetHolidays=new MutableLiveData<>();
//Your API call code goes here
return MutableLiveDataGetHolidays;
}
来源:https://stackoverflow.com/questions/48341561/will-the-onchanged-method-trigger-just-as-we-change-the-data-even-if-we-dont