Search code examples
javaandroidandroid-lifecycleandroid-architecture-components

What is the Difference between AndroidViewModel and ViewModel in Android Architecture Components?


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.


Solution

  • 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.