Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Application or ApplicationContext to ViewModel?

I have a small question. I am working on an Android app and I am using the MVVM design pattern.

I need to pass the Application Context to some of the ViewModels and to the Repository, because of actions like: instantiating the Room Database, playing sound files, saving small data into Shared Preferences. I did that using Dependency Injection.

I know that there is only one instance of the Application Context, so there will be no memory leaks if I pass it, unlike Activity Contexts.

Here comes my unclarity: I found that passing ApplicationContext (Context instance) works, but also does Application (Application instance). What is the difference between these two options? Which one is better to pass as an argument?

like image 972
Flendor Avatar asked Sep 16 '26 14:09

Flendor


1 Answers

The Application object is literally the same object as the object returned by getApplicationContext().

If you're using an AndroidViewModel with the default factory, you'll get an Application object suitable to use as a Context (as Application extends Context).

like image 107
ianhanniballake Avatar answered Sep 18 '26 03:09

ianhanniballake



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!