我正在从视图模型中的数据库获取LiveData>。但是我必须在列表中添加一些Foo对象,然后才能将它们转发到视图。
我正在使用Room API来访问数据库。我正在使用带有Dao,存储库和视图模型的推荐封装。该存储库仅转发来自Dao的LiveData。 在视图模型中,我从存储库中调用方法并将结果存储在变量中。因为我无法使用LiveData对象的观察方法,所以我尝试了Transformations.map方法。但是映射方法不会在任何时候被调用。
public class FooViewModel extends AndroidViewModel {
private LiveData<List<Foo>> fromDatabase;
private MutableLiveData<List<Foo>> forView;
public FooViewModel(/*...*/) {
//...
forView = new MutableLiveData<>();
}
//Returns the LiveData<List> for the view, that should be observed
public LiveData<List<Foo>> getViewList() {
return forView;
}
//Loads the data from the database, modifies it and maps it to the LiveData for the view
public void loadFromDatabase(/*Some conditions for query*/) {
fromDatabase = repository.getData(/*Some conditions*/);
Transformations.map(fromDatabase, (foos) -> {
forView.setValue(fillList(foos));
return forView;
}
}
//Fills the list with some other foos
private static List<Foo> fillList(List<Foo> foos) {
//Fill the list
}
}
在视图中,我以这种方式观察列表:
public class FooActivity {
protected void onCreate(/*Some inputs*/) {
viewModel.getViewList().observe(this, (foos) -> /*Display the list*/);
viewModel.loadFromDatabase(/*with some conditions*/);
}
}
然后什么也没有发生... 我还尝试转发从存储库中获取的LiveData并对其进行观察。该观察效果很好。但不是修改过的。
答案 0 :(得分:0)
//Loads the data from the database, modifies it and maps it to the LiveData for the view public void loadFromDatabase(/*Some conditions for query*/) { fromDatabase = repository.getData(/*Some conditions*/); Transformations.map(fromDatabase, (foos) -> { forView.setValue(fillList(foos)); return forView; } }
这将永远无法进行。 fromDatabase
被替换,但是转换是针对先前的fromDatabase
实例完成的。
您需要将查询条件设置为MutableLiveData
,对它进行Transformations.switchMap
才能返回LiveData<List<T>>
,并通过DAO应用正确的过滤器。
然后,如果您修改条件实时数据,则DAO将使用新条件重新评估新列表。