1 year ago

#238572

test-img

msc87

LiveData stops observing when fragment is destroyed

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.

android

kotlin

android-recyclerview

android-livedata

observers

0 Answers

Your Answer

Accepted video resources