Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android MutableLiveData keeps emitting when I re-enter fragment

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?

like image 798
Amin Keshavarzian Avatar asked Oct 19 '19 15:10

Amin Keshavarzian


People also ask

Why is Onchanged being called when I navigate back to a fragment?

This is expected because you are resubscribing to a LiveData, and LiveData replays its last emitted value when you subscribe to it.

How do I stop LiveData from observing on Android?

You should manually call removeObserver(Observer) to stop observing this LiveData. While LiveData has one of such observers, it will be considered as active. If the observer was already added with an owner to this LiveData, LiveData throws an IllegalArgumentException .

Why LiveData Observer is being triggered twice for a newly attached observer?

It does not trigger a notification. The state changes of the lifecycle alone trigger the notification of the new new view. It's just fine, that the observer is called upon creation. So it can fill itself with the initial data of the view model.


Video Answer


1 Answers

In the simple way You could set null for your MutableLiveData after getting data in onchange method of the observer. For more information you can read this article:livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case . also you can see this question maybe help you: How to clear LiveData stored value?

like image 55
maryam Avatar answered Sep 30 '22 01:09

maryam