【发布时间】:2020-08-28 08:29:42
【问题描述】:
我试图在这个片段中只发出一次,它在我第一次进入这个片段时发出,但是如果我导航到下一个片段并返回,它会再次发出,我不希望那样,因为它会重新获取我的数据,相反,如果我回到这个片段,我想避免重新获取。
片段
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
}
val fetchShopList = locationQuery.distinctUntilChanged().switchMap { location ->
liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
emit(Resource.Loading())
try{
emit(repo.getShopList(location))
}catch (e:Exception){
emit(Resource.Failure(e))
}
}
}
在这里,当我转到下一个片段并返回时,位置并没有改变。任何想法如何解决这一问题 ?我正在使用导航组件。
【问题讨论】:
-
如果您进行底部导航,请停留在片段上并在底部导航的同一片段上点击两次,它会一次又一次地发出值,然后它不是 viewModel 观察者问题,但您的片段会重新创建,我有点同意下面是@Joozd 的回答......以及为什么你在 switchMap 块中阅读不同的情况?在存储库中执行此操作并保持 switchMap 有点干净。
标签: android android-fragments kotlin mvvm android-architecture-navigation