MVVM-4: ViewModels should not refer to View-specific components.


Description

Passing context to ViewModel instances can result in a dangerous practice. In fact by storing the reference to an Activity in a ViewModel, once the Activity gets destroyed (e.g., due to a screen rotation), a memory leak could occur. By quoting a Google Android Developer Advocate: “The consumer of the data should know about the producer, but the producer - the ViewModel - doesn’t know, and doesn’t care, who consumes the data.” In order to adhere to this guideline, the LiveData architectural class provided by the Jetpack library can be used, so that Activities can simply observe the changes of the ViewModel’s data.

Example

We created a simple MVVM example.

Our viewModels do not store activities or instances of an activity in the view model.

Check this page to view the complete repository.