当片段被销毁时,LiveData 停止观察
我有几个片段(假设 A、B 和 C)相互替换。在片段 A 中,有一个 recyclerView 应该在观察者收到 liveData 中的更改时更新。但是当我移动到片段 B 时,观察者不会收到更新,因为片段 A 已经被销毁。 我已将 lifeCycle 所有者从 viewLifeCycleOwner 更改为此(片段),但结果仍然相同。
这是我的代码的一些片段:
class MainActivity: AppCompatActivity() {
val fragments = listOf(fragmentA(), fragmentB(), fragmentC())
private fun moveToFragment(index: Int) {
if (fragments.isNotEmpty()) {
viewModel.selectedPage = index
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragments[index])
transaction.commit()
}
}
}
class FragmentA(): Fragment{
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
fragmentAViewModel.listOfThings.observe(viewLifecycleOwner) { things ->
things?.let {
when (things.status) {
Status.SUCCESS -> {
thingsAdapter.submitList(things.data)
}
else -> {
thingsAdapter.submitList(emptyList())
}
}
}
}
}
我知道“替换”会破坏片段,但我也尝试使用隐藏/显示片段,但这种模式将片段重叠在一起,我无法修复它。
我的问题是这里的最佳实践是什么,以确保在进入片段之前观察者/recyclerView已经更新。否则,recyclerView 将具有旧值,并且在我转到fragmentA 后几毫秒内它们会发生变化。最明显的情况是,当 recyclerView 应该是空的,但当我转到fragmentA 时,项目在消失之前仍然存在一段时间。
I have couple of fragments (lets say A,B and C) replacing each other. In fragment A, there is a recyclerView which should be updated as an observer receives changes in a liveData. But the observer does not receive updates when I move to fragment B because fragment A is already destroyed.
I have changed the the lifeCycle owner from viewLifeCycleOwner to this (fragment) but still the same result.
Here is some snippet of my code:
class MainActivity: AppCompatActivity() {
val fragments = listOf(fragmentA(), fragmentB(), fragmentC())
private fun moveToFragment(index: Int) {
if (fragments.isNotEmpty()) {
viewModel.selectedPage = index
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragments[index])
transaction.commit()
}
}
}
class FragmentA(): Fragment{
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
fragmentAViewModel.listOfThings.observe(viewLifecycleOwner) { things ->
things?.let {
when (things.status) {
Status.SUCCESS -> {
thingsAdapter.submitList(things.data)
}
else -> {
thingsAdapter.submitList(emptyList())
}
}
}
}
}
I know that "replace" destroys the fragments but I also tried using HIDE/SHOW fragments but this pattern overlays fragments on top of each other and I wasn't able to get it fixed.
My question is what the best practice is here to make sure that the observer/recyclerView is already updated before going to the fragment. Otherwise the recyclerView will have old values and they change in few milliseconds after I go the fragmentA. The most obvious situation is when the recyclerView is supposed to be empty but when I go to fragmentA items are still there for a moment before they disappear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论