Hi, I’m making an app for fun and I want to test some things; and I have a really trivial to ask the community: let’s say I have a simple GET request to receive the day of the week, and after receiving the result I have to update my view.
To handle that (simple) case from a viewModel, you prefer using a delegate or using a escaping closure ? And why ?
For example, with completion handler:
class MyViewController: UIViewController {
var day: String
let viewModel: MyViewModel
override func viewDidLoad() {
super.viewDidLoad()
viewModel.getDay = { day in
guard let unwrappedDay = day else { return }
self.day = unwrappedDay
}
}
}
class MyViewModel {
func getDay(completion: @escaping ((_ day: String?) -> Void)) {
Service.getDay { result in
completion(result.day)
}
}
}
}
And with delegate:
class MyViewController: UIViewController, MyViewModelDelegate {
var day: String
let viewModel: MyViewModel
override func viewDidLoad() {
super.viewDidLoad()
viewModel.delegate = self
viewModel.load()
}
func updateDay(day: String) {
self.day = day
}
}
protocol MyViewModelDelegate {
func updateDay(day: String)
}
class MyViewModel {
weak var delegate: MyViewModelDelegate?
func load() {
Service.getDay { result in
self.delegate?.updateDay(day: result.day)
}
}
}
}
I’ve always used the first because it’s less to code and I find it more readable but I know a lot of people use the second way and I feel like I’m missing something !
Thanks 😀