所以我来自 MVP 背景... 我基本上想做的是,一旦我们开始从 Room (SQLite) 获取数据,就启动一个 loadingView,在成功时停止 loadingView,所有这些逻辑都应该在我的 ViewModel 中处理(试图保持我的 fragment 干净) fragment 的类。
我现在所做的是我有两个 LiveData:
- 我来自数据库的实际数据
- fragment 状态的实时数据:
我的意思是:
enum HomeState{
LOADING,
LIVE
}
private LiveData<List<SomeData>> someData;
private MutableLiveData<HomeState> homeState;
我正在我的 fragment 中观察两者,我想让我的 homeStateLiveData 确定 fragment 是否应该显示加载 View 。正如您可能看到的那样,这不会起作用,因为当新数据出现时它会立即消失到 fragment ,我无法从 ViewModel 控制 homeState 逻辑
最佳答案
As you can probably see, this won't work as when the new data comes it immediately goes to the fragment and I can't control the homeState logic from the ViewModel
您可以通过将自己置于 fragment 的观察者和数据库的 LiveData 之间来控制基于数据库 LiveData 的 homeState。执行此操作的方法是通过转换或通过 MediatorLiveData。
// with a Transformation
// this would be the method which returns the database LiveData
public LiveData<List<SomeData>> getDatabaseData() {
// the view should show a loading indicator
homeState.setValue(HomeState.LOADING);
// we don't actually map anything, we just use the map function to get
// a callback of when the database's LiveData has finished loading
return Transformations.map(dao.getSomeData(), list -> {
// the database has just finished fetching the data from the database
// and after this method returns it will be available to the observer
// in the fragment.
// we also need to dismiss the loading indicator
homeState.setValue(HomeState.LIVE);
return list;
});
}
对于 MediatorLiveData,您可以做类似的事情,只需让 MediatorLiveData 监听数据库 LiveData 并在添加数据库 LiveData 作为其源时更新它设置的观察者中的 homeState。
如果你想对此进行抽象,你可以将从数据库中获取的数据和状态(正在加载或可用)包装到一个类中,然后将你的 ViewModel 更改为仅返回具有该类的 LiveData。体系结构组件指南有 an example (有点相关)关于你如何做到这一点,他们在那里监视网络的状态,但你可以很容易地使它适应你的数据库场景。
关于android - 使用 Room Livedata MVVM 时如何显示 LoadingState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55050582/