Skip to content

Why MVVM?

Valdio Veliu edited this page Mar 29, 2020 · 3 revisions

MVVMs main focus is "separation of concerns". What does this mean? Simply put, to separate the user interface logic from the business logic or in other words, keep the UI clean so it can be easy to manage. MVVM pattern fits nicely for data-centric applications, with apps that load data from a database (CRUD) applications.

This architectural pattern is constructed of the following layers:

  • MODEL: Is data-centric, represents the entities and models of the business logic.
  • VIEW: is as "dumb" as possible. It's responsible for implementing the visual parts of the application and in the general case it must not contain any logic that requires unit-testing. Its only role is to observe (subscribe to) a ViewModel observable to get data and update the UI accordingly and to handle events towards the app and update the ViewModel so it can revise the data accordingly. 
  • VIEW-MODEL: Interacts with Model and prepares observables for the View. ViewModel should be decoupled from the View and should not be aware of the View it's interacting with. 
  • Sometimes represented in this architectural pattern we find something called REPOSITORY. Repository, or sometimes referred to as "SERVICES", acts as the single source of truth for all the data of handles in the application.

The following diagram is a representation of the data flow in MVVM applications.

MVVM diagram

The flow!

Based on the flow represented in the diagram is pretty clear that Views can only access data through a View-Model and can request changes to those data again through a View-Model. The View-Model acts as an intermediate between the presentation part of the app with the data part and the only gateway from which the data passes through.

In this demo app, the REPOSITORY is created to consider the redux store as the single source of truth for the app. Even in the case that the redux data is outdated the app will consider them as valid up until a fresh feed of data is retrieved from a webService. Since there is a persistence layer applied to the redux store the app will contain its data persistence even when the app closes and in the event that the app is re-opened the redux store will be restored to the last known state that it was before.

This offers this setup an out of the box data caching mechanism for the redux store. Meaning that the app will preload all existing data from the state and render them until a response has been retrieved from an external webService/API to refresh the data.

This explains the flow of the data clearly. Everything important to the state of the app is managed through redux utilizing the MODELS classes and their toJson & fromJson methods to parse data from the API also from the cache in case of a redux rehydration/restore. More on this will be explained in the MODEL classes structure.

Clone this wiki locally