Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should the fragment view model be created?

I have always created the view model in the onCreate method of a fragment. I have also seen some other developers creating the view model in the onCreateView method. However today i used the Android Studio template for 'Fragment with ViewModel' and the view model was created in the onActivityCreated method. Which approach is correct? If the Android Studio template is doing this in the onActivityCreated then surely there must be a reason behind this. Can any one shed light on the correct approach here?

like image 278
Dishonered Avatar asked Dec 03 '25 04:12

Dishonered


1 Answers

If the Android Studio template is doing this in the onActivityCreated then surely there must be a reason behind this.

Guess the creators of the template missed the memo that onActivityCreated will be deprecated.

I have always created the view model in the onCreate method of a fragment. I have also seen some other developers creating the view model in the onCreateView method.

Theoretically you should be creating it in onCreate, but due to how the NavHostFragment shares the same onCreate dispatch as the regular fragments, you have to rely on onCreateView or onViewCreated when you are using NavGraph-scoped ViewModels with a SavedStateHandle.

Therefore, a lazy initialization inside onViewCreated using by viewModels is your safest bet.

like image 187
EpicPandaForce Avatar answered Dec 04 '25 16:12

EpicPandaForce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!