Suppose I have views like this:
struct Parent: View {
var data: Int
var body: some View {
Child(state: ChildState(data: data))
}
}
struct Child: View {
@StateObject var state: ChildState
var body: {
...
}
}
class ChildState: ObservableObject {
@Published var property: Int
...
init(data: Int) {
// ... heavy lifting
}
}
My understanding is that the init
method for Child
should not do any heavy computation, since it could be called over and over, by SwiftUI. So heavy lifting should be done in the ChildState
class, which is marked with the @StateObject
decorator, to ensure it persists through render cycles. The question is, if Parent.data
changes, how do I propagate that down so that ChildState
knows to update as well?
That is to say, I DO want a new instance of ChildState
, or an update to ChildState
if and only if Parent.data
changes. Otherwise, ChildState
should not change.