I have been working on Android Architecture Components for a while which was introduced in Google IO 2017
One of their Component to avoid configuration changes issue they provide ViewModel
and AndroidViewModel
classes
As per the doc:
AndroidViewModel : Application context aware ViewModel
ViewModel : ViewModels can also be used as a communication layer between different Fragments of an Activity.Each Fragment can acquire the ViewModel
using the same key via their Activity
But for AndoirdViewModel
scenario I can get application context by extending a class to Application class
What is the actual difference between them in Android Development? Because both are attached to Activity/Fragment life cycle only.
But for AndoirdViewModel scenario I can get application context by extending a class to Application class
Creating your own custom subclass of Application
does not magically make that singleton instance available to a ViewModel
.
It is possible to create a custom subclass of Application
that has its own getInstance()
method or something to expose the singleton directly. Google does not like this pattern (and neither do I, for that matter), and so Google does not steer developers towards using it.
What is the actual difference between them in Android Development?
A ViewModel
on its own has no good way to get a Context
. AndroidViewModel
supplies an Application
for use as a Context
, and specifically supplies the Application
singleton so we are sure that the Context
itself does not represent a memory leak.
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