ViewModel and AndroidViewModel

Sometimes, your ViewModel could really use a Context. For example, you might need to format some data using a string resource, and the only way to get a string resource is through a Context.

If you need a Context in your ViewModel, Google’s official solution is AndroidViewModel. This offers a getApplication() function that you can call to retrieve the Application singleton. Application implements Context, so you can look up string resources and stuff from there. Your activity or fragment does not need to worry about this: just use ViewModelProvider and request the ViewModel. You also will extend AndroidViewModel instead of ViewModel and implement the required constructor, that takes an Application as a parameter.

Some of the examples in the upcoming chapters will use ViewModel, while others will use AndroidViewModel.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.