如何解决什么时候应该在Android上删除livedata观察器?
我正在使用LiveData
在firestore中观察一个列表。此观察结果取决于另一个认证LiveData
。
在创建新的LiveData
观察者之前,我应该删除它吗?如果我不这样做会怎样?
目前,我正在使用下一个代码删除观察者,但是如果我不需要的话,我可以对其进行极大地简化,因为我在代码中都做了相同的事情
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:我正在使用Doug Stevenson tutorial,太好了!
解决方法
如果您使用的是observe
方法,LiveData
将在onDestroy状态下自动清除。
观察者绑定到生命周期对象,并在清除之后进行清理 当它们的相关生命周期被破坏时。
可以找到更多信息here
仅当您使用observeForever
方法时,才需要手动删除实时数据。您需要手动删除它的原因是,当您使用observeForever
方法时,没有指定它的生命周期。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。