【发布时间】:2020-05-11 22:43:32
【问题描述】:
我有一个片段,我想对其数据进行一次提取,我使用distinctUntilChanged() 仅提取一次,因为在此片段期间我的位置没有改变。
片段
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))
}
}
}
现在,如果我转到下一个片段并按回,这会再次触发,我知道这可能是因为片段正在重新创建然后传递一个新的视图模型实例,这就是为什么不保留该位置的原因,但是如果我把activityViewModels作为viewmodel的实例,它也发生了同样的情况,数据在backpress上再次加载,这是不可接受的,因为每次返回都会获取数据,这对我来说不是服务器效率,我需要当用户在此片段中时仅获取此数据,并且如果他们按下回不再次获取它。
有什么线索吗?
我正在使用导航组件,所以我不能使用 .add 或进行片段事务,我想在第一次创建这个片段时只获取一次,而不是在下一个片段的后台重新获取
【问题讨论】:
-
要明确一点:问题是 fetchShopList 多次发出相同的值,还是重新计算一遍?您可以简单地通过在计算值的位置放置一个断点并进行调试来查看它是否命中断点。
-
它再次发出@Boda,感谢您的时间
标签: android android-fragments kotlin viewmodel android-architecture-components