我有一个加载产品列表的片段,然后转到另一个片段,但是当我回来时,Resource.Loading
再次被触发,显示在我的进度栏中
我正在使用导航组件,我知道我应该处理我的状态,但是我的问题是这个。
我知道livedata将存储我的数据,然后弹出该片段时,它将从livedata本身立即加载它,而不是再次检索它,但是,它还在数据列表上方显示了我的progressBar,我知道那是因为我的viewModel中的emit(Resource.Loading())
,但是...
如果我从另一个片段回来并重新创建此onActivityCreated,是否有方法不显示此进度或不发出该Loading状态?
我的片段
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel.fetchProductList()
.observe(viewLifecycleOwner, Observer {
when (it) {
is Resource.Loading -> {
showProgress()
}
is Resource.Success -> {
hideProgress()
landingAdapter.itemList = it.data
if (landingAdapter.itemCount == 0) {
Toast.makeText(
requireContext(),
"No items yet",
Toast.LENGTH_SHORT
).show()
}
landingAdapter.notifyDataSetChanged()
}
is Resource.Failure -> {
hideProgress()
}
}
})
}
ViewModel
fun fetchProductList() = liveData(Dispatchers.IO) {
emit(Resource.Loading())
try{
val getProductList = repo.getProductList()
emit(getProductList)
}catch (e:Exception){
emit(Resource.Failure(e))
}
}
在这一点上,我认为在popBackstack上重新创建片段时再次发出Resource.Loading()
再次向我显示了我的progressDialog
我尝试使用事件包装器,但它也做相同的事情
因为我使用的是livedata-ktx
,所以我不想在视图模型构造函数中加载数据,而是只想在片段中一次处理它
谢谢
Resource.Idle
,该状态在用户在当前状态为Resource.Loading
时离开时发出,并且在观察该状态时,如果其值为Resource.Idle
,则不采取任何操作。fetchProductList()
是function
NOT一个变量,将其称为creates
新的LiveData<Resource>
对象。而是尝试不使用功能:-
val productListLiveData: LiveData<Resource> = liveData(Dispatchers.IO) {
emit(Resource.Loading())
try{
val getProductList = repo.getProductList()
emit(getProductList)
}catch (e:Exception){
emit(Resource.Failure(e))
}
}