Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best place to init ViewModel in fragment onCreateView or onCreate Method?

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.

like image 905
Chetan Ansel Avatar asked Oct 02 '18 11:10

Chetan Ansel


People also ask

What is difference between onCreate and onCreateView in fragment?

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() .

Is onCreate called before onCreateView?

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() .

Can a fragment have a ViewModel?

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.


1 Answers

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.

like image 88
Florian Walther Avatar answered Oct 18 '22 19:10

Florian Walther