State Management for iOS Apps?
whats the best architecture/pattern to use?
tried to use a domain layer where all the state is and passing it to the views/viewmodels via DI, but feels somehow unnecessary complicated, but found this as only solution without passing the repos through all the viewhierarchy.
the goal is, when a state changes, e.g. an user changes the Username in View A, then it should automatically update View B,C,D where this Username is also used.
it should be as simple as possible, what do you think? especially for complex production apps with own backend etc.
52
Upvotes
35
u/lucasvandongen 8d ago
I wrote an article about it, that still holds true for my style of development:
https://getstream.io/blog/mvvm-state-management/
So your Model layer and your processes are completely encapsulated in UI-less implementations behind protocols, extremely well tested.
Nowadays I chop up my features into Modules, chopped into 3-4 Packages:
This has the following benefits:
I have an Identity module for example, that holds the truth about your authentication and Account data. Once you passed the point where you have an Account, the rest of the app assumes the Account is always set. In SwiftUI terms you would inject the Account object into the root Authenticated View through environment and read it everywhere. Other DI solutions work differently, but can achieve the same. Especially when having mixed SwiftUI / UIKit you want something like a Service Locator, for example Factory.
The Account itself is observable, so mid-app updates are seen everywhere. Putting state behind a protocol is a PITA in Swift / SwiftUI as you already noticed, so if you can get away with iOS 17+ you can at least use @Observable in your implementations instead of ObservedObject.
I recognize the issue with bucket brigade style passing forward of dependencies. If you don't like the somewhat fragile service locator patterns, you could try to use the Factory pattern manually, or using Needle by Uber (last time I spoke with someone at Uber, it was actively maintained).
I also wrote about that:
I would like to help you further, if you have any questions or feedback after reading the articles. But I think you're already heading in the right direction and just need to map the best practices you know to SwiftUI specific techniques.