【问题标题】:room LiveData how to ignore some properties change房间LiveData如何忽略一些属性变化
【发布时间】: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()
})

p1p7 的属性不断变化。由于列表一直在刷新。

现在,我可以通过检查来改进它

if (adapter.foos != it) {
     adapter.foos = it
     adapter.notifyDataSetChanged()
}

但这几乎没有改善。

那么如果可以通过这个来改进:(我还没有测试过)

         adapter.foos = it
         adapter.notifyDataSetChanged()
}

这可能有效,但它会继续检查 map,可能只需要取出 adapter.foos.map { a -&gt; a.code } 以节省一点。

这可能是另一种解决方法。

我还想把 code 取出并使用一个新变量 var codeObserver: MutableLiveData(List&lt;String&gt;) = 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


    【解决方案1】:

    您可以使用 AsyncListDiffer 避免重新加载回收器视图适配器。有关详细信息,请参阅Google's Documentation。简单来说,它可以使用 List 的 LiveData 中的值,并将数据简单地呈现给适配器。当接收到新列表时,它通过后台线程上的 DiffUtil 计算列表内容的差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-21
      • 2021-10-01
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      相关资源
      最近更新 更多