Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ViewModelProviders and ViewModelProvider class?

Tags:

I saw two classes with a similar name, ViewModelProviders, and ViewModelProvider. Can anyone explain what are the difference between these classes? which class actually provide the ViewModel?

like image 997
Abhishek Kumar Avatar asked Jan 21 '19 12:01

Abhishek Kumar


People also ask

What is the difference between ViewModelProvider and ViewModelProviders?

So, you can think of as wrapper around library class for ViewModelProvider . On the other hand, ViewModelProvider (belongs to Maven artifact android. arch. lifecycle:viewmodel) is class that provides ViewModels for a scope.

What is ViewModelProviders?

Public methods Creates a ViewModelProvider , which retains ViewModels while a scope of given fragment is alive. static ViewModelProvider. of(FragmentActivity activity) Creates a ViewModelProvider , which retains ViewModels while a scope of given Activity is alive.

Why do we need ViewModelProvider?

Why do we need ViewModel Factory? We are unable to create ViewModel on our own. To create ViewModels, we need the ViewModelProviders utility provided by Android. ViewModelProviders, on the other hand, can only instantiate ViewModels with the no-arg constructor.

How do I use ViewModelProvider on Android?

If your ViewModel has dependencies or arguments and you want to create your ViewModel instance, then you should create your custom ViewModelProvider. Factory and pass the dependency or arguments through the ViewModel constructor and give a value to the ViewModelProvider. Factory instance.


1 Answers

ViewModelProviders (belongs to Maven artifact android.arch.lifecycle:extensions) is a class from android.arch.lifecycle package which contains utilities methods for ViewModelStore class & returns you object of ViewModelProvider class when you use of() method from it.

So, you can think of as wrapper around library class for ViewModelProvider.

On the other hand, ViewModelProvider (belongs to Maven artifact android.arch.lifecycle:viewmodel) is class that provides ViewModels for a scope. So it's default ViewModelProvider for an Activity or a Fragment can be obtained from ViewModelProviders class.

So, yes ! this is the main class that provides core logic for your ViewModel, but you'll need to obtain it from ViewModelProviders which returns you this class to obtain ViewModel from.

Edit:

After ViewModel version 2.2.0:

Class ViewModelProviders has been deprecated and we can now use ViewModelProvider directly by creating it's new instance for getting ViewModel.

Something like this: ViewModelProvider(this).get(SomeViewModel::class.java)

like image 73
Jeel Vankhede Avatar answered Oct 23 '22 19:10

Jeel Vankhede