提问者:小点点

为什么SavedStateHandle不保存或返回我的LiveData?


我使用导航组件并在一个RecolyerView(MVVM架构,所以这个片段有一个viewmodel)中加载数据,如果我移动到另一个片段,然后导航回到有viewmodel的片段,那么viewmodel的livedata是空的,但我不知道为什么。如果我正确地知道,我就不需要手动调用SavedStateHandle.set来持久化数据,因为SavedStateHandle无论如何都会这样做。我将place对象存储在livedata中,并且该类是extends Parcelable。

ViewModel:

类OverviewViewModel(私有值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
     
     }
}

地点:

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

我订阅livedata的更改,然后调用getall:

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


overviewViewModel.getAllPlacesFromRepository(...)

共1个答案

匿名用户

你能展示一下你是如何在你的片断里初始化你的VM的吗?

请确保发送savedstate,如下所示:

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