Search code examples
androidandroid-architecture-components

AndroidViewModel vs passing Application context to ViewModel


The documentation states the following:

If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.

Code example:

class MainViewModel(application: Application) : AndroidViewModel(application) {
... 
}

Two questions:

  1. How does the AndroidViewModel helps me if I need to pass Application to ViewModel's ctor anyway?
  2. And again, if I need to pass Application, why do I need AndroidViewModel? I can just use ViewModel and pass it Application.

Solution

  • If you're providing your own factory, you can pass anything you want to a regular ViewModel object, you're correct about that.

    However, if you are using the default factories, the source code shows that the default factories only fill in the Application instance for you if your ViewModel extend AndroidViewModel.