【发布时间】:2019-08-31 10:33:48
【问题描述】:
我目前有一个项目,其中包含 MyItem 列表,并使用 Firebase/LiveData。它分为组,每个组都有项目。
如果发生以下任何情况,我希望能够更新此列表:
- 项目已更新(通过 Firebase 在后端)
- 过滤器已更改(Firebase 上为每个用户创建一个单独的表)
- 已为项目添加了书签(Firebase 上为每个用户提供了一个单独的表格)
为了获取内容列表,我有一个类似这样的函数来返回 LiveData,它会在项目更新时更新(#1)。
数据库
getList(id: String): LiveData<List<MyItem>> {
val data = MutableLiveData<List<MyItem>>()
firestore
.collection("groups")
.document(id)
.collection("items")
.addSnapshotListener { snapshot, exception ->
val items = snapshot?.toObjects(MyItem::class.java) ?: emptyList()
// filter items
data.postValue(items)
}
return data
}
在我的 ViewModel 中,我有处理这种情况的逻辑。
视图模型
private val result = MediatorLiveData<Resource<List<MyItem>>>()
private var source: LiveData<List<MyItem>>? = null
val contents: LiveData<Resource<List<MyItem>>>
get() {
val group = database.group
// if the selected group is changed.
return Transformations.switchMap(group) { id ->
// showing loading indicator
result.value = Resource.loading(null)
if (id != null) {
// only 1 source for the current group
source?.let {
result.removeSource(it)
}
source = database.getList(id).also {
result.addSource(it) {
result.value = Resource.success(it)
}
}
// how to add in source of filter changes?
} else {
result.value = Resource.init(null)
}
return@switchMap result
}
}
逻辑相当复杂,难以理解。有没有更好的方法来构建它来处理多个不同的变化?存储用户当前过滤器的最佳方式是什么?
谢谢。
【问题讨论】:
标签: android kotlin google-cloud-firestore android-livedata mutablelivedata