从房间数据库检索LiveData自动更新吗?



我在我的接口中有一个方法,它从我的房间数据库中作为LiveData列表检索所有记录。我的方法如下:

@Query("SELECT *FROM task_table ORDER BY taskId DESC")
fun getAll():LiveData<List<Task>>

我有以下代码在我的ViewModel类:

val tasks:LiveData<List<Task>> = taskDao.getAll()

我也有一个观察者设置在我的片段如下:

//After some other code and code to create an instance of the ViewModel
viewModel.tasks.observe(viewLifecycleOwner, Observer {
it?.let {
adapter.data = it
}
})

我对LiveData有点困惑。当我添加一条新记录到我的房间数据库,我的LiveData它自己更新而不需要调用

getAll()方法。当你有LiveData,当你在数据库中添加/删除/更新记录时,Android操作系统更新这个列表吗?谢谢。

当你观察LiveData时,只要viewLifeCycleOwner处于以下状态之一,你就会得到新的数据:Lifecycle.State.STARTEDLifecycle.State.RESUMED。所以你的假设是正确的。

请在这里阅读更多关于观察LiveData的信息。

  1. @Query("SELECT * FROM Brands order by _id")
    fun getAll(): List<BrandEntity>
    
  2. class BrandViewModel : ViewModel() {
    private val _list = MutableLiveData<List<BrandEntity>>().apply {
    value = AppDatabase.get().brandsDao().getAll()
    }
    val list: LiveData<List<BrandEntity>> = _list
    }
    
  3. val viewModel = ViewModelProvider(this)[ProductsViewModel::class.java]
    viewModel.list.observe(viewLifecycleOwner) {
    }
    

最新更新