ViewModels request new data each time view is recreated
See original GitHub issueIf PlantListFragment or GardenPlantingListFragment are recreated, their ViewModels make a new database request instead of returning the last value held by the livedata.
For example:
fun getGardenPlantings() = gardenPlantingRepository.getGardenPlantings()
fun getPlantAndGardenPlantings() = gardenPlantingRepository.getPlantAndGardenPlantings()
The Arch docs say this is a not to do this (link):
private LiveData<String> getPostalCode(String address) {
// DON'T DO THIS
return repository.getPostCode(address);
}
The UI component then needs to unregister from the previous LiveData object and register to the new instance each time it calls getPostalCode(). In addition, if the UI component is recreated, it triggers another call to the repository.getPostCode() method instead of using the previous call’s result.
The Arch components BasicSample shows a better way to implement this using MediatorLiveData (link)
When I implemented this myself, using the MediatorLiveData also fixed #10 https://github.com/chris-feldman/android-sunflower/blob/master/app/src/main/java/com/google/samples/apps/sunflower/viewmodels/PlantListViewModel.kt
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:8 (8 by maintainers)
Top GitHub Comments
Hi @sagar-viradiya - yes, please open a new issue and we can discuss the livedata changes there.
Sure, I’ll see if I can get one together today 👍
On Tue, Jun 5, 2018, 11:21 PM Tiem Song notifications@github.com wrote: