我进入 FragmentA()后,转到 FragmentA(),将数据提取到服务器,当数据到时,我将填充一个列表。
现在,如果我从 FragmentA()转到 FragmentB(),然后从 FragmentB()我按返回按钮或导航回 FragmentA(),它将列表重新引用到服务器并重新填充到服务器再次。
我不希望这样,而是希望我的viewmodel方法不再触发,我正在寻求该帮助。导航组件不允许我执行.add操作来保存 FragmentA()的状态
无论如何,这样做是一次获取操作,而不是每次做backpress时都重新获取我从FragmentB()到FragmentA()的时间?
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()
}
}
})
}
View 模型
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在其latest updated best practice architecture components github repository中确实是这样的:
fun setId(owner: String, name: String) {
val update = RepoId(owner, name)
if (_repoId.value == update) {
return
}
_repoId.value = update
}
这样,即使重新创建了片段,只要viewmodel仍处于 Activity 状态,就不会向服务器请求新数据,但livedata会再次发送其最新数据,以便片段可以更新其 View 。另外,您是否认为 locationQuery.distinctUntilChanged()无法正常工作?您是否正在监视是否将请求发送到服务器?