5 A Quick Recap

MVVM Architecture

Before you create your first view model, I want to revisit the internals of the Model-View-ViewModel pattern. We need to keep the following in mind:

MVVM Architecture
MVVM Architecture

These are the four key elements you need to remember for this and the next chapters. Let me show you what happens when the view controller needs to display a piece data in the view it manages.

An Example
An Example

The view controller asks its view model for a piece of data. The view model asks the model it manages for the raw value, a timestamp for example. The view model applies the necessary transformations to the raw value and returns a value the view controller can immediately display to the user in its view.

That’s the flow we will see time and time again in the next chapters. The view controller is no longer responsible for transforming the raw values of the model and it doesn’t even know about the model. That’s an important difference with the Model-View-Controller pattern.

Naming the View Model

A common question is “How should I name the view model?” There are several opinions and the best advice is “Do what feels right and makes sense. And, more importantly, make sure you understand the code you write today a year from now.”

The view models I create are very often focused on a specific view controller. For example, we’ll create a view model for the day view controller and a view model for the week view controller. Because the view model is linked to the view of a view controller, I name the view model after the view it’s used for.

[View]ViewModel

For example, we’ll name the view model for the day view controller DayViewViewModel. You’re free to choose the name of your view models, but I recommend that you use the ViewModel suffix to clearly indicate that you’re dealing with a view model.