I have this basic Android Architecture Component use-case where I observe a live-data and update UI.
myLiveData.observe(viewLifecycleOwner, Observer {
// update UI
})
// will trigger a network call and update the repository (Room DB)
myViewModel.refreshDataFromRepository()
With the observe call, I get the trigger and I update the UI, which is fine. However, I also need to update the DB if the backend data has changed, so I trigger a network refresh and that updates the DB and triggers the observer once again. So, I am getting data twice.
I can change conflict strategy to ignore to avoid but I need to set it to "replace" as the data may change:
@Query("SELECT * FROM my_table ORDER BY timestamp DESC")
fun getMyEntities(): LiveData<List<MyEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun add(myEntity: MyEntity)
Other option is to compare the network response with DB contents and avoid re-writing identical data but would be expensive.
Is there any way, database access can be made intelligent to avoid trigger if data has not changed?
You could use distinctUntilChanged, it has been added to Transformations:
myLiveData.distinctUntilChanged().observe(viewLifecycleOwner) {
// update UI
}