Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 859
Refael Sheinker Avatar asked Jun 18 '26 14:06

Refael Sheinker


2 Answers

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.

like image 177
ianhanniballake Avatar answered Jun 20 '26 08:06

ianhanniballake


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.

like image 32
Pawel Avatar answered Jun 20 '26 08:06

Pawel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!