[英]When should i remove livedata observer on android?
I am observing a list in firestore using LiveData
.我正在使用
LiveData
观察 firestore 中的列表。 This observations is dependent on another authentication LiveData
.此观察结果取决于另一个身份验证
LiveData
。
Should i remove the old LiveData
observer before creating the new one?在创建新观察者之前,我应该删除旧的
LiveData
观察者吗? What will happen if i don't?如果我不这样做会发生什么?
Currently i am removing the observer using next code but i can simplify it greatly if i won't need to since i do the same all over my code目前我正在使用下一个代码删除观察者,但如果我不需要,我可以大大简化它,因为我在我的代码中都做同样的事情
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
...
//Authentication observer which is the ItemAuto dependent
viewModel.auth.observe(viewLifecycleOwner, Observer {auth ->
updateUserItemAutoLiveData(auth)
})
}
private fun updateUserItemAutoLiveData(auth: Auth) {
if (!auth.uid.isNullOrEmpty()) {
removeUserItemAutoObservers()
itemAutoLiveDate = viewModel.getUserItemAutoLiveData(auth.uid)
itemAutoLiveDate!!.observe(viewLifecycleOwner, Observer {
if (it != null) {
if (it.data != null) {
itemAutoCompleteAdapter.submitItemAuto(it)
}
}
})
} else {
removeUserItemAutoObservers()
}
}
private fun removeUserItemAutoObservers() {
if (itemAutoLiveDate != null && itemAutoLiveDate!!.hasObservers()) {
itemAutoLiveDate!!.removeObservers(this)
}
}
ps: i am using Doug Stevenson tutorial which is great! ps:我正在使用Doug Stevenson 教程,这很棒!
If you are using observe
method, LiveData
will be automatically cleared in onDestroy state.如果您使用
observe
方法, LiveData
将在onDestroy 状态下自动清除。
Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.
观察者绑定到 Lifecycle 对象并在其关联的生命周期被销毁时自行清理。
More information can be found here更多信息可以在这里找到
You need to remove livedata manually only if you use observeForever
method.只有在使用
observeForever
方法时才需要手动删除livedata。 The reason why you need to remove it manually is because when you use observeForever
method, you don't specify the lifecycle of it.之所以需要手动移除,是因为在使用
observeForever
方法时,没有指定它的生命周期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.