Why SavedStateHandle doesn't save or return my livedata?

2.2k views Asked by At

I use Navigation Component and load data in a recyclerview (MVVM architecture so this fragment has a viewmodel) if I move to another fragment and then I navigate back to the fragment which has a viewmodel then the viewmodel livedata is empty but I don't know why. If I know correctly I don't need to manually call savedStateHandle.set to persist the data because savedStateHandle does it anyway. I store Place objects in the livedata and this class is extends Parcelable.

ViewModel:

class OverviewViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {

     companion object {
          private const val SAVED_All_PLACES_LIVEDATA_KEY = "savedAllPlacesLiveDataKey"
     }

     private val repository: PlacesRepository = PlacesRepository(this)

     private var allPlacesList: MutableList<Place> = mutableListOf()
     var allPlacesLiveData: MutableLiveData<MutableList<Place>> = savedStateHandle.getLiveData<MutableList<Place>>(SAVED_All_PLACES_LIVEDATA_KEY)

     fun getAllPlacesFromRepository(...)
          repository.getAllPlaces(...) //when successfully gets the data then call the viewmodel's addAllPlacesLiveData function
     }

     fun addAllPlacesLiveData(sites: List<Site>) {
          allPlacesList.clear()
          val places = mutableListOf<Place>()
          for(i in 0..9) {
               val site = sites[i]
               val distance = site.distance / 1000
               val place = Place(site.name, site.formatAddress, distance)
               places.add(place)
          }
          places.sortBy {
               it.distance
          }
          allPlacesList.addAll(places)
          allPlacesLiveData.value = allPlacesList
     
     }
}

Place:

@Parcelize
data class Place(
    var name: String = "",
    var address: String = "",
    var distance: Double = 0.0
) : Parcelable

I subscribe for the changes of the livedata and then call getAll:

overviewViewModel.allPlacesLiveData.observe(viewLifecycleOwner) { places ->
            recyclerViewAdapter.submitList(places.toMutableList()) }


overviewViewModel.getAllPlacesFromRepository(...)
1

There are 1 answers

1
Iván Garza Bermea On

Could you show how you're initializing your VM inside your Fragment?

Make sure you send over the savedState like this:

private val viewModel: YourViewModel by viewModels {
        SavedStateViewModelFactory(requireActivity().application, this)
    }