lundi 6 décembre 2021

How Model notifies its change to ViewModel in iOS MVVM pattern

Most articles about MVVM describe when the model is changed, for example when new data is made available and we need to update the UI, the Model notifies the View Model.

But I don’t get how Model communicate with View Model to notify about its change.

In the code below, I used property observer to bind View and ViewModel. And I know that I can change my Model by assigning new value like self.person.value.name = name in ViewModel.

I read a lot of articles about mvvm and think I wrote an appropriate example as follows, but even in this code I cannot get the concept that Model notifies its change to ViewModel. In my code below, does model notifies viewmodel about its change? Can you explain with examples?

class Observable<T> {
    var value: T {
        didSet {
            self.listener?(value)
        }
    }
    
    var listener: ((T) -> Void)?
   
    init(_ value: T) {
        self.value = value
    }
    
    func subscribe(listener: @escaping (T) -> Void) {
        listener(value)
        self.listener = listener
    }
}

struct Person {
    var name: String
    var age: Int
}

struct MyViewModel {
    var person: Observable<Person>
    
    init(person: Person) {
        self.person = Observable(person)
    }
    
    func changePersonName(with name: String) {
        person.value.name = name
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var infoLabel: UILabel!
    
    let viewModel = MyViewModel(person: Person(name: “Mike“, age: 100))
    
    override func viewDidLoad() {
        viewModel.person.subscribe { [weak self] person in
            self?.infoLabel.text = person.name + “& " + "\(person.age)"
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire