Home > Enterprise >  Does LiveData retrieved from the Room Database update automatically?
Does LiveData retrieved from the Room Database update automatically?

Time:11-30

I have a method in my Interface that retrieves all records from my Room Database as a LiveData List. My method is as follows:

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

I have the following code in my ViewModel class:

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

Also I've got an Observer setup in my Fragment as follows:

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

I'm a bit confused with LiveData. When I add a new record to my Room Database, my LiveData<List> updates on it's own without me having to call the

getAll() method. When you have LiveData, does the Android OS updates this List when you add/delete/update a record in the Database? Thanks.

CodePudding user response:

When you observe LiveData, you will get the new data as long as the viewLifeCycleOwner is in one of the following states: Lifecycle.State.STARTED or Lifecycle.State.RESUMED. So your assumption is correct.

Please read more about observing LiveData here.

CodePudding user response:

Yes Its obviously updating If you read the documentation then that the observer changes automatically. and update.

CodePudding user response:

STEP 1 @Query("SELECT * FROM Brands order by _id") fun getAll(): List

STEP 2 class BrandViewModel : ViewModel() {

private val _list = MutableLiveData<List<BrandEntity>>().apply {
    value = AppDatabase.get().brandsDao().getAll()
}
val list: LiveData<List<BrandEntity>> = _list

}

STEP 3 val viewModel = ViewModelProvider(this)[ProductsViewModel::class.java] viewModel.list.observe(viewLifecycleOwner) {

}

  • Related