Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context in MVVM in android

Tags:

android

mvvm

I have started working on MVVM architecture for android application.I have a doubt that is it right to pass the context to view model ? If not then how can my view model can access the context if needed.

I am doing the following things:

  1. Feed data using some EditText.
  2. Send this data to View model.
  3. View model send this data to repository
  4. Repository storing this data to shared preferences of the device.

As shared preferences required context to instantiate the object.

I am new to this architecture any guidance would be helpful for me, thanks in advance.

like image 959
Lalit Kushwah Avatar asked Oct 03 '17 05:10

Lalit Kushwah


2 Answers

You should use AndroidViewModel() in the ViewModel, pass application:Applicatoin, and use getApplication() to get the context.

ViewModel Example:

class MainTrendsViewModel (application: Application) : AndroidViewModel(application) {
    // ViewModel must extend AndroidViewModel(), and pass application to it. 
    // Code here and
    // use getApplication() to get context
}

Other anwer that work for me that you could reference: reference answer that works for me

like image 81
QuartZ Avatar answered Oct 09 '22 23:10

QuartZ


I think the use of ApplicationContext is ok, You can extend your ViewModel from AndroidViewModel and whenever you need a reference to the context use getApplication() methods.

Even better, if your using dagger, you don't need this at all, you just inject your ApplicationContext where ever you need it. It can be in your view model or a utility class that handles shared preference, etc.

like image 39
Alireza A. Ahmadi Avatar answered Oct 10 '22 00:10

Alireza A. Ahmadi