4

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.

Burhanuddin Rashid
  • 5,260
  • 6
  • 34
  • 51
  • you are asking 2 things in same question, I believe you can switch the title and focus it about why use AndroidViewModel instead extending Application. The answer that @CommonsWare gave is still valid. In that way you can ask to remove the "duplicated" tag because create a new question for a good answer... I don't think is a good idea. – MiguelHincapieC Jan 26 '18 at 13:41

1 Answers1

15

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    Out of curiosity why doesn't Google (or you) like the subclass of Application with getInstance() ? – neteinstein Jun 13 '18 at 14:36
  • 4
    @neteinstein: I can't speak for Google. I'm not a fan as it makes using `Application` too easy, and many times `Application` is the wrong type of `Context` to use. – CommonsWare Jun 13 '18 at 22:30