Let’s get started
In this article, I am going to build an app that lists the assets available for investing with MVVM architecture and I named it“MyPortfolio”.
Model
The Model represents the data consumed by the application. A set of structs or classes that define the information that would be used (and eventually rendered by a view). In our example, we are going to add our instrument model here.
View
The View only consists of visual elements. Instrument UITableViewCell goes here which contains the title and subtitle of UI Labels. as. This can be extended with other UI elements like images, graphs, etc; as the development grows.
ViewModel
The ViewModel provides a set of properties that represents each UI component available in the View. Interfaces and UI Controls are connected with a technique called “binding” ( I will explain this in upcoming articles). For now, we are going to stick with the simple ViewModel.
ViewController
This is the place where we will be using our InstrumentViewModel. Since this is the first iteration of the app, I thought of keeping it super simple. I am directly creating a ViewModel property that holds the object for the data flow. Now the InstrumentsViewController looks like this on being tailored with the UITableView.
DataFlow
We have almost done everything. It’s playing time. Press Cmd + R to view the output.
- When the app starts, our InstrumentsViewController will appear on the screen.
- When the instance of the ViewController is created, the instrumentsTableView property gets initialized and triggers the data source call.
- This is the time where ViewModel gets loaded on the ViewController since it's marked as lazy. Once the loading gets completed successfully, the table view automatically populates the list of instruments.
- As a result, we can see a list of instruments being displayed in the table view. Tapping on each cell will send the user interaction to the ViewModel to initiate further routing.
Earlier in MVC, we might have followed a folder structure where we group all the view controllers, cells, and views together.
Whereas in MVVM we are going to segregate things as Model | View | ViewModel | ViewController.
Using the above method, we can manage the whole project in a better way.
You can download the sample project available on GitHub by clicking here.
Wrapping Up
We have done the super simple first iteration of “MyPortfolio”. In, upcoming weeks we can derive a new combination with the following MVVM patterns :
- MVVM + POP
- MVVM + SwiftUI
- MVVM + Combine + SwiftUI
- MVVM + RxSwift
- MVVM + Swinject + RxSwift
I hope you enjoyed this article 😀. Please feel free to share, comment, and give some claps 👏👏. Stay tuned at this pace for more updates. Thanks for reading this.