Search code examples
androidmvvmandroid-context

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?


Solution

  • 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).