android - ViewModel 发出多次而不是一次
问题描述
我试图在这个片段中只发出一次,它在我第一次进入这个片段时发出,但是如果我导航到下一个片段并返回,它会再次发出,我不希望这样,因为它会重新获取我的数据,相反,如果我回到这个片段,我想避免重新获取。
分段
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))
}
}
}
在这里,当我转到下一个片段并返回时,位置不会改变。任何想法如何解决这一问题 ?我正在使用导航组件。
解决方案
这就是LiveData
工作原理,它会在恢复时始终为您提供最新信息。我建议使用 kotlin Flow
,因为这可以满足您的要求,在您完成发射后,您将不再获得更新
推荐阅读
- javascript - 我的 for 循环在 chrome 上不起作用,但在 firefox 上起作用
- web-scraping - 使用 Python 抓取特定的复选框值
- reactjs - 映射时如何将每个单选按钮与对象相关联
- cudd - CUDD BDD:构建一个布尔值作为连词的析取但得到运行时错误:分段错误
- html - CSS 颜色父行
- google-apps-script - 是否可以在 Google-sheets API v4 中批量保护工作表?
- git - 创建 Git Rebase 别名
- google-apps-script - 更改文件/文件夹的 DriveApp.Permission
- javascript - 检查字符串中的特定子字符串模式并获取其所有匹配项
- c - Do/While 无法识别字符以在 C 中结束循环