Android Architecture ViewModel Context Components

I am exploring Google architecture components for implementing ViewModel and LiveData for my application, and the official documentation says that:

Note. Because the ViewModel highlights specific actions and fragmentation, it should never reference a view or any class that might contain a reference to an activity context. If the ViewModel needs an application context (for example, to search for a system service), it can extend the AndroidViewModel class and have a constructor that gets the application in the constructor (because the Application class extends the context)

After that, I got the following code:

public class ViewModelTest extends AndroidViewModel {

public ViewModelTest(Application application) {
    super(application);
}

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

And should I usually instantiate it for activity?

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

? SharedPreferences -, ? , ViewModel ? , , . , , .

+4
1

AndroidViewModel android.arch.lifecycle, Android. , . .

ViewModel , , Activity, Activity.

ViewModel , , .

+1

Source: https://habr.com/ru/post/1685954/


All Articles