I have been trying to create an Object of ViewModel in an Activity but ViewModelProviders is deprecated So what\'s the alternative to create the ViewModel\'s object.
Instead of ViewModelProviders
we should now use ViewModelProvider
constructors and it has three:
public ViewModelProvider(ViewModelStoreOwner owner)
public ViewModelProvider(ViewModelStoreOwner owner, Factory factory)
public ViewModelProvider(ViewModelStore store, Factory factory)
1. If you are not using a ViewModelProvider.Factory
to pass additional arguments to your ViewModel
, you can use the first one. so:
viewModel = ViewModelProviders.of(this).get(YourViewModel.class);
can be replaced with:
viewModel = new ViewModelProvider(this).get(YourViewModel.class);
AppCompatActivity
and different kinds of Fragment
s are indirect subclasses of ViewModelStoreOwner
(see the complete list of its known subclasses here), so you can use them in this constructor.
2. But if you are using a ViewModelProvider.Factory
, you should use the second or the third constructors:
viewModel = ViewModelProviders.of(this, viewModelFactory).get(YourViewModel.class);
can be replaced with:
viewModel = new ViewModelProvider(this, viewModelFactory).get(YouViewModel.class);
OR based on the documentation of ViewModelStore
:
Use ViewModelStoreOwner.getViewModelStore() to retrieve a ViewModelStore for activities and fragments.
viewModel = new ViewModelProvider(getViewModelStore(), viewModelFactory).get(YourViewModel.class);