What is ViewModelStore and viewModelStoreOwner?

Anmol picture Anmol · Nov 16, 2019 · Viewed 7.2k times · Source

I am very confused due to this new ViewModelProvider api(ViewModelProviders is deprecated)

As with the new changes there are new Constructors also (Source code).

#1

public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
        this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
                ? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
                : NewInstanceFactory.getInstance());
    }

#2

public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
        this(owner.getViewModelStore(), factory);
    }

#3

 public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
        mFactory = factory;
        mViewModelStore = store;
    }

Gradle Depenedency:

implementation "androidx.lifecycle:lifecycle-extensions:2.2.0-rc02"

So These Constructor's require ViewModelStore and viewModelStoreOwner.

Doc:

@param store {@code ViewModelStore} where ViewModels will be stored.

@param owner a {@code ViewModelStoreOwner} whose {@link ViewModelStore} will be used to retain {@code ViewModels}


Can anyone define them and how to use them and what they really mean to us developer's?


is ViewModelStoreOwner==activity/fragment?

Answer

Sagar picture Sagar · Nov 16, 2019

Can anyone define them and how to use them and what they really mean to us developer's?

A ViewModelStore can be considered as a container that stores the ViewModels in a HashMap. Where the key is string value and value is the ViewModel being saved(ViewModelProvider uses a concatenation of the string_key + ViewModel class canonical name).

A ViewModelStoreOwner is merely an interface. Any class that implements the getViewModelStore() defined by this interface becomes the owner of ViewModelStore. This class then maintains the ViewModelStore and should be responsible to appropriately restoring it when needed.

We can implement our own version of the owner and the state based on the requirement.

is ViewModelStoreOwner==activity/fragment?

Yes. Based on the Android source code, both Fragment (from androidx.fragment.app) & ComponentActivity (from androidx.activity) implements ViewModelStoreOwner. These classes maintains a viewModelStore and value is restored appropriately.