Hi,
I'd like to know if there are any good patterns to follow for state management in SwiftUI?
A quick google search returns me a few approaches on Redux like architecture but given the
Combine framework
and likes such as the
ObservableObject
+
EnvironmentObject
, which seems closer to what
Context API
in
Reactjs
represents for most cases, it might be unnecessary.
Ideally, I'd like to find ways in the
SwiftUI
world to help me assess the app performance, which could help me find patterns or architectures to solve state management in my applications, so any tips or advice in these regards will be extremely beneficial for me to learn if you don't mind sharing!
Meanwhile, I find that I can look into redrawing to identify occurrences but wonder about other approaches that might be more suitable or can provide better insight, let's look at my cavemen, not the best example and a bit of a pseudo-code:
// My ObservableObject
class Hunter: ObservableObject {
@Published var name = "Fred Flinston"
@Published var gun = "Rock"
...
}
// CaveView
struct CaveView: View {
@EnvironmentObject var hunter: Hunter
var body: some View {
print("[DEBUG] redraw happend!")
...
}
}
// Main view
struct HunterLand: View {
// @EnvironmentObject var hunter: Hunter
var body: some View {
// print("[DEBUG] redraw happend!")
VStack {
CaveView()
...
}
}
}
The
Main View
represented above as
HunterLand
has a nested view that is subscribed to the
Hunter
ObservableObject instance (resolved in the
sceneDelegate
); The
Main View
has nested views and only the
CaveView
will be affected by any observable changes. The commented out parts is to expose that if it also subscribed the
redrawing
would happen twice in principle.
It's my understanding that the diff algorithm for SwiftUI probably takes care of a lot of stuff for us, but would be nice to know how to verify how it performs when developing and making architecture choices to better improve the app experience or any good reads or best practices in this regard.
Thank you!