Mommy, Where Does a ViewModel Come From?

You might think that you create a ViewModel via whatever constructor you set up for it.

Instead, the Architecture Components expect you to get a ViewModel instance by using ViewModelProvider. A ViewModelProvider instance is tied to either:

If you do not have one of those, you cannot use ViewModelProvider.

If you do have one of those, call the static of() method on the ViewModelProviders class (note the plural) to get a ViewModelProvider (note the singular) tied to your FragmentActivity or Fragment. This ViewModelProvider is tied to the logical instance of this activity or fragment, regardless of configuration changes. So, if the activity is destroyed and recreated as part of a configuration change, you will get the same ViewModelProvider instance in the new activity as you had in the old one.

Then, to get a ViewModel, call get() on the ViewModelProvider, passing in the Java class object for your subclass of ViewModel (e.g., MyViewModel.class). If there already is an instance of this ViewModel tied to this ViewModelProvider, you get that instance. Otherwise, a fresh instance will be created for you, from the zero-argument constructor. If using the zero-argument constructor is not what you want, you can:

So, in the typical case, you wind up with code like this:

    TripRosterViewModel vm=
      ViewModelProviders.of(this).get(TripRosterViewModel.class);

Here, this inherits from the Fragment backport, and we are retrieving a TripRosterViewModel to use in that fragment.

We will see this code snippet again in the next section.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.