I tested the code in the Gist’s out and it works as described Jose!
I’ve been attempting to implement a different version of the above where my Fragment only listens to a single Observer when the ViewModel updates data (normal intended use).
However, I’m seeing multiple LiveData Observers triggered in a Fragment after navigating to a new Fragment, popping the new Fragment, and returning to the original Fragment as outlined in this StackOverflow.
Details: The architecture consists of MainActivity that hosts a HomeFragment as the start destination in the MainActivity’s navigation graph. Within HomeFragment is a programmatically inflated PriceGraphFragment. The HomeFragment is using the navigation component to launch a new child Fragment ProfileFragment. On back press the ProfileFragment is popped and the app returns to the HomeFragment hosting the PriceGraphFragment. The PriceGraphFragment is where the Observer is being called multiple times.
- Creating the Fragment’s ViewModel in the onCreate() method.
priceViewModel = ViewModelProviders.of(this).get(PriceDataViewModel::class.java)
- Moving methods that create the Observers to the Fragment’s onCreate() method.
thisfor the LifecycleOwner in the method
observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer).