Android ViewModel Sharing Between Fragments

826 views Asked by At

My team is just beginning to transition our app over to using ViewModels in Android and need some assistance. Our app has a collection of buildings displayed in a fragment. You can select a building in the list to view details about that building in detail fragment.

We are trying to share data between fragments by using the suggested way here (binding the ViewModel to the activity): https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

Our BuildingViewModel has a masterList of buildings and a detail record. The BuildingCollectionFragment has an observer on the masterList and the BuildingDetailFragment has an observer on the detail object.

The problem we are running into is that buildings can have related buildings on the DetailFragment that you can navigate to. When you select a building in the detail list of related buildings, we call the following code before we transition to the new BuildingDetailFragment

buildingViewModel.detailObject.value = item!!.building

This works out great!

Problem

The problem is when we press the back button, the ViewModel, that is still bound to the activity, still thinks the building that we were looking at before pressing the back button is still active. We would like to just use the existing list and not have to go back out and get data from the API

0

There are 0 answers