Android ViewModel观察者永远不会被调用

时间:2019-10-24 10:05:15

标签: android viewmodel observer-pattern

我有以下代码:

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);
            }
        });
    }
}

以及onCreate方法上的MainActivity:

    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);被设置

2 个答案:

答案 0 :(得分:1)

也许您的drivers.setValue(d);return 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();

答案 1 :(得分:1)

drivers.setValue()更改为drivers.postValue(,如果有帮助,则应更改定义的 Suraj Vaishnav 之类的代码,在订阅以下内容后调用 loadDrivers 观察者。