Junior — Middle
Is it possible to do without using StateObject in certain scenarios?
sobes.tech AI
Answer from AI
Yes, in some scenarios, it is possible to do without using @StateObject.
@StateObject is intended for creating and storing an ObservableObject inside a View so that it persists across redraws. If the object is created and managed outside the View (for example, in a parent component or through Dependency Injection), then child Views can use @ObservedObject or @EnvironmentObject to access this object without needing to recreate it.
Example:
class Model: ObservableObject {
@Published var value = 0
}
struct ParentView: View {
@StateObject private var model = Model()
var body: some View {
ChildView(model: model)
}
}
struct ChildView: View {
@ObservedObject var model: Model
var body: some View {
Text("Value: \(model.value)")
}
}
Here, @StateObject is used only in the parent View, and the child receives a reference through @ObservedObject. Thus, if the object is created outside the View or passed from above, @StateObject is not mandatory.