我进入FragmentA(),在进入FragmentA()之后,我将数据提取到服务器中,当这些数据到来时,我将填充一个列表。
现在,如果我从FragmentA()转到FragmentB(),然后从FragmentB()按下返回按钮或导航回FragmentA(),它将列表重新获取到服务器并再次填充列表。
我不希望这样做,而是希望我的viewmodel方法不再触发,我正在寻求帮助,sinde Navigation Components不允许我执行.add操作来保存FragmentA()的状态
无论如何,做一次按下操作时,是否将它作为一次一次提取操作而不是每次从FragmentB()到FragmentA()时都进行重新提取?
private val viewModel by viewModels<LandingViewModel> {
VMLandingFactory(
LandingRepoImpl(
LandingDataSource()
)
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sharedPref = requireContext().getSharedPreferences("LOCATION", Context.MODE_PRIVATE)
val nombre = sharedPref.getString("name", null)
location = name!!
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
fetchShops(location)
}
private fun fetchShops(localidad: String) {
viewModel.setLocation(location.toLowerCase(Locale.ROOT).trim())
viewModel.fetchShopList
.observe(viewLifecycleOwner, Observer {
when (it) {
is Resource.Loading -> {
showProgress()
}
is Resource.Success -> {
hideProgress()
myAdapter.setItems(it.data)
}
is Resource.Failure -> {
hideProgress()
Toast.makeText(
requireContext(),
"There was an error loading the shops.",
Toast.LENGTH_SHORT
).show()
}
}
})
}
private val locationQuery = MutableLiveData<String>()
fun setLocation(location: String) {
locationQuery.value = location
}
fun fetchShopList(shopId:String) = locationQuery.distinctUntilChanged().switchMap { location ->
liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
emit(Resource.Loading())
try{
emit(repo.getShopList(shopId,location))
}catch (e:Exception){
emit(Resource.Failure(e))
}
}
}
如何只在FragmentA()处一次获取这些值,并将这些值保留在viewmodel中,然后在尝试进行重新获取时不再进行此操作?
我很想知道如何使这项工作!
谢谢
全能的Google在其最新的更新的最佳实践架构组件github存储库中做到了:
fun setId(owner: String, name: String) {
val update = RepoId(owner, name)
if (_repoId.value == update) {
return
}
_repoId.value = update
}
这样,即使重新创建了片段,只要viewmodel仍处于活动状态,就不会向服务器请求新数据,但livedata会再次发送其最新数据,以便片段可以更新其视图。
此外,您是否locationQuery.distinctUntilChanged()无法正常工作?您是否正在监视是否将请求发送到服务器?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句