Reputation: 205
I have a concept question about MVVM. I'm learning this pattern in swift 3.
This is my situation: I have a screen with a list of users. The UserViewModel has a property that is a list of users, but the controller shouldn't know about the User model. I read that controller shouldn't know absolutely nothing about the models.
If the controller requests data from a user of this list, this data must be a dictionary of data or can be a User model?
Then, the UserViewModel must contain also the same properties than the User model?
Thank you for your help.
Upvotes: 0
Views: 701
Reputation: 424
MVVM:
Model: Will be the Schema of your Request and API response
View: Viewcontroller will watch for the change published by the View Model
ViewModel: Will broadcast the change/result/response coming from the API
In Swift:
To Update the ViewController about the change in Model from the ViewModel is done through Observer Pattern.
ViewModel will publish and update the Model object and send the message through observer that a change has taken place.
The Viewcontroller on the other hand would execute the binding function for update the UI with the Published objects from View Model
In SwiftUI:
It has its own Pub-Sub pattern, which can be achieved by Published objects and StateObject/ObservedObject property wrappers.
Here view model Publishes the Model Object using @Published
. View Model can only Publish if it is inheriting from Observable Protocol. The Published Model becomes a publisher that emits the data.
In the view side, @StateObjects, @ObservedObjects
are both used to hold the published values so that it can be used when the view is redrawn.
Upvotes: 1
Reputation: 6018
If the controller requests data from a user of this list, this data must be a dictionary of data or can be a User model?
Data can be the UserModel
.
Then, the UserViewModel must contain also the same properties than the User model?
Hhm. Of course not. Why UserViewModel
should have same properties that UserModel
have? There is no any reason for that.
For purpose when you need to return some userModel.name
property to controller, you can and should get this only from property of UserModel
, i.e. get the right UserModel
from ViewModel
and than get the property:
func controllerFunc() {
let userModel = viewModel.getUserModelFromList()
print(userModel.name)
}
But in case when you need to prepare value for controller, you can create property in ViewModel
, that contains some sort of modification for UserModel
's property. And controller should get property from ViewModel
, not from UserModel
.
I read that controller shouldn't know absolutely nothing about the models.
Well, ideally - yes. Also, should be mentioned that ViewModel
shouldn't know anything about UI components, i.e. ViewModel
shouldn't have import UIKIt
statement.
For example, if you need an UIImage
, you should return name (String
type) of image from ViewModel
and create UIImage
object in controller.
Upvotes: 1