Chapter 6. Reactive view models

 

In this chapter

  • Working with view models and the view
  • Using view models in the file browser example
  • Working with view models as sources of view data
  • Using view models on the Android platform

The view layer

UI programming has come a long way in recent years with different kinds of architectures and paradigms. The only thing that doesn’t change is separating the logic from the rendering. On a practical level, you usually put the code that determines what the program looks like visually in one file, and the information to display in another file.

The line is sometimes admittedly blurry, but let’s look at a few examples of what’s considered rendering and what’s considered logic:

Rendering

Logic

  • The size and color of a spinning loader
  • The visibility of a loading spinner
  • The position of a thumbnail of a list item
  • The logic to get the necessary data to show on a list
  • The positions of circles and crosses on a grid of tic-tac-toe
  • Game rules that determine what a player is allowed to do

Typically, you try to put these two responsibilities into different places (classes, files of code). The rendering part is called the view.

View

Here are the key characteristics of a view:

  • Occupies a part of the visible screen
  • Decides how the pixels it contains are rendered
  • Represents the endpoint of data processing
  • Can contain light logic, such as drop-down states

Platform containers

View models

The blueprint of a view model

Connecting views and view models

The whole picture

View model lifecycle

Coffee break

View models and the Android lifecycles

The view affinity of the code

Summary