Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
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.

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda