Home > Back-end >  Android Navigation LiveData stopped observing when fragment goes to background
Android Navigation LiveData stopped observing when fragment goes to background

Time:10-11

I have 2 fragments that i navigate throught navigation component from Jetpack. When i go back from fragment 2 to fragment 1, i fire an event throught livedata from fragment 2 and fragment1 should be observing. Althought, fragment 1 didnt observed and when i sste a breakpoint to check how many observers liveData has, it say 0. Code below

class Fragment1 :
Fragment() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
   
      myViewModel.selectedItem.observe(viewLifecycleOwner, {
            println("Observed")
        })
 findNavController().navigate(
                    Fragment1Directions.actionToFragment2()
                )
}


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    myViewModel = ViewModelProvider(requireActivity()).get(MyViewModel::class.java)
}

private lateinit var myViewModel: MyViewModel

}

class Fragment2 : Fragment() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)


    myButton.setOnClickListener{
        MyViewModel().selectItem(true)
        findNavController().navigateUp()
    }
}

}

class MyViewModel : ViewModel() {

private val mutableSelectedItem = MutableLiveData<Boolean>()
val selectedItem: LiveData<Boolean> get() = mutableSelectedItem

fun selectItem(value: Boolean) {
    mutableSelectedItem.value = value
}

}

CodePudding user response:

It's strange to not have observer for

myViewModel.selectedItem.observe(viewLifecycleOwner, {
            println("Observed")
        })

when it's called onViewCreated and with viewLifecycleOwner, but it looks like you have a mistake for creating common ViewModel for Fragment1 and Fragment2

Both should use

myViewModel = ViewModelProvider(requireActivity()).get(MyViewModel::class.java) to get same ViewModel for both fragments

  • Related