"Slicing" the View Model

For background, I’m nearing completion of an app I plan to publish. The app is built with SwiftUI and uses MVVM. As the project has evolved, my view model has grown quite large, with a view hierarchy 5 views deep. I include an environment object instance of my view model in nearly every view.

I came across this article in one of the newsletters I subscribe to. Since I’ve not seen this subject in any tutorial or discussion on CWC, I thought I’d mention it. The idea is to divide your view model into smaller “slices” and use only the slice you need for any given view. This will prevent the unnecessary re-rendering of views (when view model data that those views don’t depend on changes).

I plan to try implementing the idea in my project, but was curious as to whether anyone out there has tried it, or has thoughts or opinions. It seems like a good way to improve the efficiency of an app.

1 Like

The programming answer for anything is “it depends”

For this, it depends on what efficiency you’re trying to solve.

Re-rendering views is pretty inexpensive and may not help the performance of the app tremendously.

But generally a good thought from this article is only letting the views that need it, have the proper control.

Meaning you want the smallest scope possible for controlling (changing) variables

If your whole app has access to an object. And there’s a bug because one variable is getting changed, but you don’t know where. It is difficult to pinpoint the problem, when “everyone” can change that value.

When only 2 views can change a value rather than 10, it becomes much easier to find the culprit.

1 Like

Thanks for the advice. I did give it a shot; unfortunately most of my views use most of the view model data, so it’s hard to find a good way to split up the properties and methods. This being the case, and with what you’ve said about re-rendering views being inexpensive, I think it would probably be more trouble than it’s worth.

I take your point about limiting the scope of variables. For now this app runs bug-free. If that changes, I may get some experience with what you’re talking about. :grimacing:

1 Like

You’ll get there :joy: the bugs have to grow lol

It’s entirely dependent on how your app is laid out and what the data is, for whether or not it’s worth splitting up stuff

1 Like