Refael Sheinker
Refael Sheinker

Reputation: 891

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.

Upvotes: 8

Views: 8819

Answers (2)

ianhanniballake
ianhanniballake

Reputation: 199805

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.

Upvotes: 10

Pawel
Pawel

Reputation: 17248

You can write your custom ViewModel without extending AndroidViewModel and it will be functionally identical.

Only difference is default ViewModelFactory checks if ViewModel is an instance of AndroidViewModel and invokes one-arg constructor passing down Application context automatically.

Upvotes: 2

Related Questions