T
T
Tkas2019-02-01 08:42:34
iOS
Tkas, 2019-02-01 08:42:34

Using static properties in the viewModel in the MVVM pattern in the case of "one view model - several views". Is this approach correct?

There is one view model with a number of properties (name and age). The first view controller displays the values ​​of these properties (eg Joe 30). When you click on the button, you go to the second view controller, in which you can edit these two values ​​(for example, Misha 40). Accordingly, when returning to the first view controller, these new values ​​\u200b\u200bshould be displayed in the labels. This problem can be solved in two ways: it is to use static properties:

class ViewModel {
    static var name = BehaviorRelay<String>(value: "Joe")
    static var age = BehaviorRelay<String>(value: "30")
}

Either pass self
class ViewModel {
    var name = BehaviorRelay<String>(value: "Joe")
    var age = BehaviorRelay<String>(value: "30")
    
    func foo() -> ViewModel {
        return self
    }
}

Question: which of these approaches is correct? Or can it be done somehow differently by making another view model (EditViewModel, for example (but in this case I don’t know how to update the data in the first view))?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
briahas, 2019-02-07
@Tkas

In my opinion, you do not correctly understand the meaning of the view model:
- they only draw on it.
- no one changes
the view model - the view model is created only from the model
That is, it turns out that you have a model in which there is data in some form.
This model that also is transferred everywhere between .
And now, when you need to display the data, the necessary view model is generated from the model.
That is, the answer to your question will be the following - pass the model (which is better to be a structure) between the controllers, and they will take the view model they need from it and show it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question