【发布时间】:2022-01-03 09:57:32
【问题描述】:
我正在使用 room 查询并返回 LiveData 以在 UI 上显示元素。问题是实体经常更改大多数属性,这与 UI 无关,并且由于多次刷新 UI 并没有带来任何好处。
我想要的是 swift combine @Published.
代码如下:
@Entity
@Parcelize
data class Foo(@PrimaryKey var code: String,
var p1: Double,
var p2: Int? = null,
var p3: Int? = null,
var p4: Double? = null,
var p5: Int? = null,
var p6: Double? = null,
var p7: Int? = null
): Parcelable
其实我只关心code的属性更改插入/删除。
@Query("SELECT * FROM Foo WHERE code IN (:fooIds)")
fun getLiveDataListBy(fooIds`: List<String?>): LiveData<List<Foo>?>?
我在 ViewModel 中有该属性并在片段中观察它。
var foosLiveData: LiveData<List<Fool>>? = null
viewModel.foosLiveData?.observe(viewLifecycleOwner, {
adapter.foos = it
adapter.notifyDataSetChanged()
})
p1 到 p7 的属性不断变化。由于列表一直在刷新。
现在,我可以通过检查来改进它
if (adapter.foos != it) {
adapter.foos = it
adapter.notifyDataSetChanged()
}
但这几乎没有改善。
那么如果可以通过这个来改进:(我还没有测试过)
adapter.foos = it
adapter.notifyDataSetChanged()
}
这可能有效,但它会继续检查 map,可能只需要取出 adapter.foos.map { a -> a.code } 以节省一点。
这可能是另一种解决方法。
我还想把 code 取出并使用一个新变量 var codeObserver: MutableLiveData(List<String>) = MutableLiveData()
然后
viewModel.foosLiveData?.observe(viewLifecycleOwner, {
viewModel.codeObserver.value = it.foo.map { it.code}
})
viewModel.codeObserver.observe(viewLifecycleOwner, {
adapter.foos = viewModel.foosLiveData?.value
adapter.notifyDataSetChanged()
}
好吧,我没有测试上面的代码,但看起来方向不对。
那么有什么更好或更正确的方法来实现只观察一个或几个属性?
【问题讨论】:
标签: android kotlin android-livedata