Reputation: 891
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:
Application
to ViewModel's ctor anyway?Application
, why do I need AndroidViewModel? I can just use ViewModel and pass it Application
.Upvotes: 8
Views: 8819
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
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