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?
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.
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 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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With