While building apps using Swift and SwiftUI you'll be following the MVVM architecture which consists of three distinct holes within your application.
- The Model, which is responsible for holding your application's data and being the source of truth of your app.
- The View, which, by name, you can guess that consists the view part of your app, where you'll write everything that it's related to your UI (buttons, lists, avatar and so on...)
- The ModeView acts more like a "glue" between your Model and your View. He is responsible for enabling the communication between your view and your model, acting like a bridge or a middle agent between the two of them.
But how exactly does the
ModelView guarantees this communication between the
Model and the
Basically this communication happens by following a pattern of listening to changes, publishing that changes have occurred and "listening" to these publications.
So anytime a change of data happens in the
ModelView is subscribed to these changes, listening to when they happen:
And after a change of data occurs, and ModelView detects it, what happens?
From this point, the ModelView will be responsible for publishing that a change happened. The view will be observing for these publications and will update the interface
Now, let's take a look at how the communication happens starting from the
View part of our application:
View -> ModelView -> Model
Suppose that in our interface we have a button that increments a counter. How does this update happens?
When the user clicks in this button, he has the intent of incrementing the counter. So, we expose to the
View through the
ModelView something that we could call as "Intent functions". They are just regular functions that will be called from an interaction that happens in our interface.
So in this simple case mentioned above, the button fires an intent to increment the counter.
When this function (for instance
incrementCounter()) is invoked from the button click the
ModelView will simply update the
Model variable which holds the current counter value.
From this point the cycle basically repeats. After the counter value is updated, the
ModelView will publish that this value was updated, the
View will listen to this publication, get the new counter value and update the interface.
The final flow would look close to this:
These were just a few notes about the MVVM, there's no detail on how to implement this on an actual code base as I intend to this in a next article.