Dishonered
Dishonered

Reputation: 8841

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?

Upvotes: 3

Views: 1986

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81559

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.

Upvotes: 4

Related Questions