I am using live data with ViewModel.
I have a scenario where I have two fragments and One Activity. Fragment A and Fragment B.
From Activity, I have launched Fragment A (its shows list of names i.e fetch from backend) and when I tap on Name its displays Fragment B(that's is back stack).
Now from Fragment B if I press the back button, it returns to fragment A, it shows a blank screen as I have implemented ViewModel in the onCreate method of fragment A.
But if I have implemented the ViewModel in the oncreateView method of fragment A, it will keep on adding observers as the fragment is not destroyed.
onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity. onCreate() .
The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView() .
In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.
To avoid keeping additional Observers
in onCreateView
, pass getViewLifecycleOwner()
as the LifecycleOwner
to the LiveData
's observe
method. This will remove the previous Observer
as soon as the fragment
's View
is destroyed.
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