I have been using MVC since my first app on iOS... now i want to try MVVM.
My approach is that a Model can contain the remote URL and the ViewModel makes the request to download the image. (pushing then to binded view)... I think this is suitable so as to avoid making a network request in Views (or even worse, cells!)
class Person: NSObject {
var firstName: String?
var lastName: String?
var avatarURL: URL?
}
class PersonEntryViewModel {
var name:String?
var avatarImage:UIImage?
init(person: Person?) {
super.init()
// omitted: binding self.name based on person.firstName & person.lastName
var request: URLRequest? = nil
if let avatarURL = person?.avatarURL {
request = URLRequest(url: avatarURL)
}
fetchImageFromNetwork({ response, data in
if let data = data {
avatarImage = UIImage(data: data)
}
})
}
}
What do you think?
My doubts are about memory. I could have a big array of viewmodels filled with UIImages...
If each cell is holding its own PersonEntryViewModel
and that is getting discarded in the cell's prepare for reuse, then memory isn't a problem because images will be discarded at the same time.
I think it would be best not to put the download code in the init method. Better would be to have some sort of trigger method you can call when the view model is passed to the cell.
It really depends on what the larger architecture looks like.
If you want to see some examples of handling images in an Rx-MVVM-C app there are a couple of great ones in the RxSwift slack channel:
https://rxswift.slack.com/archives/CTSAM9V27/p1583148003073800 https://rxswift.slack.com/archives/CTSAM9V27/p1583149698079500
Join the discussion by going here: https://rxslack.herokuapp.com