Android MutableLiveData keeps emitting when I re-enter fragment

Viewed 1835

I'm using a shared ViewModel in Navigation component rather than creating a ViewModel for every fragment (mostly because it's easier) but now I have a problem when I re-enter a fragment and subscribe to the ViewModel live data of that fragment, I get the last state also too.

here is the ViewModel Code:

  val apiLessonData: MutableLiveData<String>> = MutableLiveData()
  fun getLessonsUserCreated() =
        apiCall(MyMaybeObserver(apiLessonData))

in MyMaybeObserver, I have somthing like this:

override fun onSuccess(t: T) {
    apiDataObserver.postValue(t)
}

and this is how I observe it in my fragment:

private val apiAddGoalData = Observer<String> { response ->
    showSnack(response)
}

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        .
        .
        viewModel.apiAddGoalData.observe(viewLifecycleOwner, apiAddGoalData)
        .
        .
    }

now when I enter the first time it works fine but I open it the second time, it shows the snack from the previous time, how to stop this without creating new ViewModel?

2 Answers

I don't think your problem is with the LiveData since you are wisely using the viewLifecycleOwner, problem is with the state of the view and lifeCycle of the fragment. With navigation component of jetpack, fragments get replaced in the container. Think of this scenario: You open fragment A then you navigate to frament B and press back button to return to fragment A. onCreateView and onViewCreated methods of the fragment A gets called again. Since the onDestroy of fragment A haven't been called when you opened fragment B some of the view states will be restored while returning to A. This is as you might know the same reason we use viewLifecycleOwner. So Nullify or clear the state of the views in the onDestroyView of the fragment A:

recyclerView.setAdapter(null)
checkBox.setChecked(false)
Related