我有以下代码:
public class ViewModelDrivers extends ViewModel {
private MutableLiveData<List<DriverDetailsModel>> drivers;
public LiveData<List<DriverDetailsModel>> getDrivers() {
if (drivers == null) {
drivers = new MutableLiveData<>();
loadDrivers();
}
return drivers;
}
private void loadDrivers() {
CloudFactory.getInstance().getAllServerDrivers(PreferenceUtils.getInstance().getDeviceId(), new IServerAllTrucksCallback() {
@Override
public void onAllTrucks(List<DriverDetailsModel> d) {
drivers.setValue(d);
}
});
}
}
和MainActivity的onCreate方法:
ViewModelDrivers model = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(ViewModelDrivers.class);
model.getDrivers().observe(this, items -> {
//here never gets called. Why?
});
由于不推荐使用,所以我没有使用ViewModelProviders。我从未在observe()方法中收到结果。而且drivers.setValue(d);
被设置
也许您的drivers.setValue(d);
在返回drivers;
之前就已呼叫因此,从loadDrivers();
方法中删除getDrivers()
,如下所示:
public LiveData<List<DriverDetailsModel>> getDrivers() {
if (drivers == null) {
drivers = new MutableLiveData<>();
}
return drivers;
}
并在设置观察者之后从loadDrivers()
调用,如下所示:
model.getDrivers().observe(this, items -> {
//here never gets called. Why?
});
loadDrivers(); //here call loadDrivers();