我目前有一个包含MyItem列表并使用Firebase / LiveData的项目.它分为几组,每个组都有项目.
如果发生以下任何情况,我希望能够更新此列表:
>一项已更新(通过Firebase在后端)
>过滤器已更改(每个用户在Firebase上的单独表)
>将项目添加为书签(在Firebase上每个用户一个单独的表)
为了获得目录列表,我有一个类似这样的函数来返回LiveData,该LiveData将在项目更新时更新(#1).
getList(id: String): LiveData> {
val data = MutableLiveData>()
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>>()
private var source: LiveData>? = null
val contents: LiveData>>
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
}
}
逻辑非常复杂,很难遵循.有没有更好的方法来构造它来处理多个不同的更改?存储用户当前过滤器的最佳方法是什么?
谢谢.