Modelview and viewpager2: how can I stop to observe the liveData when the page is not visible?

Viewed 487

This is my issue recipe:

  • a fragment container
  • a fragment container viewmodel
  • viewPager 2
  • N fragments and for each fragment I have a modelView
  • repository shared between the modelView

Inside the repository I have a LiveData and in each modelview I use the trasformations.map method to observe it and trasform it in a liveData observed by the inner fragment.

My problem happens when I swipe the page, because the fragment not visible continues to observe the repo live data and the relative fragment continues to be triggered.

The following is the inner fragment onActivityCreated:

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

    ......

    viewModel.getRowItems().observe(viewLifecycleOwner, Observer {
        baseTableAdapter.refreshList(it)
    })
    .....

This is the innerFragment's viewModel getRowItems() method:

fun getRowItems(): LiveData<Array<out RowItem>> {
    return Transformations.map( repository.getRowListLiveData()
    ) {
        ....
      }
    }
}
0 Answers
Related