JamitLabs / JamitFoundation

JamitFoundation is a collection of useful concepts to enable composition oriented development with UIKit
MIT License
10 stars 5 forks source link

Update view model properties #55

Open PaMicht opened 3 years ago

PaMicht commented 3 years ago

I was wondering if there is no cleaner way of updating immutable ViewModel properties than doing that inside a StatefulViewController:

var actualModel = self.model
actualModel.isLoading = true
self.model = actualModel

Solution 1

A suggestion would be to have an extension for StatefulViewController containing this:

import JamitFoundation

extension StatefulViewController {
    func updateModel(modifier: (inout Model) -> Void) {
        var actualModel = model
        modifier(&actualModel)
        self.model = actualModel
    }
}

Extension in action:

viewController.updateModel { $0.isLoading = true }

Solution 2

Another approach could be to allow var properties in the ViewModel. Setting a var property would automatically trigger the update mechanism of the StatefulViewController. Code example:

self.model.isLoading = true // isLoading is a var
mrylmz commented 3 years ago

I think the best solution is to allow mutable members in a ViewModel but we have to restrict all view models to be of type struct because it wouldn't work with classes.

PaMicht commented 3 years ago

I also like the 2 solution. Since structs are value types it should be no problem to have mutable properties.

PaMicht commented 3 years ago

I think the best solution is to allow mutable members in a ViewModel but we have to restrict all view models to be of type struct because it wouldn't work with classes.

One thing I just noticed: Does this mean that the update mechanism of StatefulViewController is triggered each time the ViewModel changes? Take this code for example:

self.model.isLoading = true
self.model.isRefreshing = true
self.model.title = 'Some title'

Would this update the view 3 times? If so, then tis could be a performance overhead.