我使用导航组件并在一个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(...)
你能展示一下你是如何在你的片断里初始化你的VM的吗?
请确保发送savedstate
,如下所示:
private val viewModel: YourViewModel by viewModels {
SavedStateViewModelFactory(requireActivity().application, this)
}