Home » Android » Android Architecture Components ViewModel Context

Android Architecture Components ViewModel Context

Posted by: admin May 14, 2020 Leave a comment


I’m studying google’s architecture components to implement ViewModel and LiveData to my app, and the official documentation says that:

Note: Since the ViewModel outlives specific activity and fragment instantiations, it should never reference a View, or any class that may hold a reference to the activity context. 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)

Following that, I ended up with a code like that:

public class ViewModelTest extends AndroidViewModel {

public ViewModelTest(Application application) {

public void test(){

And should I instantiante it normally on the activity?

  val viewModel2 = ViewModelProviders.of(this).get(ViewModelTest::class.java)

Isn’t it bad? To use this application variable when need to access SharedPreferences or anything that need a context?
And if it is, should I avoid using it on the ViewModel and use it only on the view? Specially if I want to update a UI component with a value that needs a context. I kinda don’t know how to approach this issue, and I’m open for any suggestions.

Thanks in advance

How to&Answers:

AndroidViewModel class is provided as part of the android.arch.lifecycle package which is part of Android’s architecture components. It itself calls for the Application Context passed into the constructor. The Application Context lives across the Activity lifecycle.

An Application context in a ViewModel is okay because the Application context is tied to the whole Application lifecycle as opposed to an Activity context, which is tied to the Activity lifecycle.

ViewModel documentation specifically is referring to not use the Activity Context, but the Application Context if fine.