The Model-View-ViewModel architecture
The MVVM architecture consists of three components:- Model represents the datasource. This layer is accessed to update/store and retrieve the data.
- View-Model exposes methods and variables for the view to use.
- View uses the variables and methods from the View-Model.
Difference MVVM and MVP
In MVVM the ViewModel exposes it's methods and variables for the View to use it. In MVP the Presenter has a one-to-one relationship with the View, and decides what the view should do.Example
We created a simple MVVM example . As you can see, the activities perform the requests: getAllNotes() and insert(note). The ViewModels, perform the requests to the Model (NoteRepository). The ViewModels have the notes ready for the Views to display. This data is in a LiveData< List < Note > >. Whenever a new Note has been added, this is directly observed in the MainActivity.Important
Always get values directly from the ViewModel, do not compute these values in the Activities, since these results can get lost.Checkout the github page to view the full repository.