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?
This is expected because you are resubscribing to a LiveData, and LiveData replays its last emitted value when you subscribe to it.
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 .
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With