Usage of @ObservedObject

Until now I have used @ObservedObject for cases, when I will use @StateObject now.

Where and how should I use @ObservedObject?

Replies

One case is when you need to pass that object down to other subviews in your hierarchy. For example:

Code Block
struct TopView: View {
@StateObject var foo: Foo = ...
var body: some View {
VStack {
...
SomeSubView(foo: foo)
}
}
}
struct SomeSubView: View {
@ObservedObject var foo: Foo = ...
var body: some View { ... }
}


Another situation: an @ObservedObject or @StateObject could have a property that is another ObservableObject. You could pass that to Views as well. In that case, since you are controlling the instantiation of the model object, I think you would use @ObservedObject, not @StateObject.
My understanding is that the key differences between @ObservedObject and @StateObject relates to ownership of the object and how likely it is for the object to be recreated.

For example, if you have a view that creates an @ObservedObject var test = Test(), every time that view is redrawn (which might be many times), it will recreate a new instance of Test. If you have a view that takes an @ObservedObject as an initialized property like
Code Block
struct Tester: View {
@ObservedObject var test: Test
var body: some View {
...
}
}

Then the test instance won't be recreated each time the Tester view is redrawn, but you're then dependent on whatever view owns the Test object to hold onto it.

@StateObject avoids much of those issues.
Code Block
struct Tester: View {
@StateObject var test = Test()
var body: some View {
...
}
}

In that example, @StateObject tells SwiftUI to hold onto the value of test, even if the view is redrawn repeatedly.