Android Architecture Components ViewModel Context

Viewed 9278

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) {
    super(application);
}

public void test(){
    Prefs.getCurrentCode(getApplication());
}

And should I instantiante it normally on the activity?

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

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

1 Answers
Related