我的viewModel重新获取我的数据,导致我的闪光灯在每次我到达这个片段时都会继续执行,而且数据也会被重新获取,这使得我的账单出现在Firebase上
如何防止每次弹出我的片段时都重新获取数据?
在我看来
viewModel.fetchShops(location).observe(viewLifecycleOwner, Observer {
when(it){
is Resource.Loading -> {
shimmer.visibility = View.VISIBLE
shimmer.startShimmer()}
is Resource.Success -> {
shimmer.visibility = View.GONE
shimmer.stopShimmer()
adapter.setItems(it.data)
}
is Resource.Failure -> {
Toast.makeText(requireContext(),"Error fetching data",Toast.LENGTH_SHORT).show()
}
}
})我在我的onViewCreated()中调用了它,所以每次这个片段重新创建我的Resource.Loading函数以及fetchShops(location),并且它再次读取到我的数据库时,我希望它每次返回到这个片段时都只读取一次,你知道吗?
ViewModel
fun fetchShops(location:String) = liveData(Dispatchers.IO) {
emit(Resource.Loading())
try{
emit(repo.fetchShops(location))
}catch (e:Exception){
emit(Resource.Failure(e))
}
}发布于 2020-05-04 07:32:47
每次调用fetchShops()时都会创建一个新的LiveData实例。这意味着以前创建的任何LiveData (以及它存储的先前的值)都会丢失。
相反,您应该通过使用location作为根据liveData with Transformations 创建liveData { }块的输入来进行Tranform your LiveData。
private val locationQuery = MutableLiveData<String>
// Use distinctUntilChanged() to only requery when the location changes
val shops = locationQuery.distinctUntilChanged().switchMap { location ->
// Note we use viewModelScope.coroutineContext to properly support cancellation
liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
emit(Resource.Loading())
try{
emit(repo.fetchShops(location))
}catch (e:Exception){
emit(Resource.Failure(e))
}
}
}
fun setLocation(location: String) {
locationQuery.value = location
}然后您可以通过更新您的片段来使用它:
// Set the current location
viewModel.setLocation(location)
// Observe the shops
viewModel.shops.observe(viewLifecycleOwner, Observer {
when(it){
is Resource.Loading -> {
shimmer.visibility = View.VISIBLE
shimmer.startShimmer()}
is Resource.Success -> {
shimmer.visibility = View.GONE
shimmer.stopShimmer()
adapter.setItems(it.data)
}
is Resource.Failure -> {
Toast.makeText(requireContext(),"Error fetching data",Toast.LENGTH_SHORT).show()
}
}
})https://stackoverflow.com/questions/61581052
复制相似问题