Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feedback: SwiftUI's Observable macro is not a drop-in replacement for ObservableObject #206

Open
malhal opened this issue Jan 15, 2025 · 2 comments

Comments

@malhal
Copy link
Contributor

malhal commented Jan 15, 2025

Using @State at the app level causes the object to be init too soon so should be avoided. E.g. it'll be init during Previews even when App's body isnt called.

Better fix is just to conform your class also to ObservableObject then you can continue to use it with @StateObject. So think of @Observable as an alternative just for @Published.

@jessesquires
Copy link
Owner

Thanks @malhal !

Yes, in some scenarios, you might have to continue using ObservableObject. It certainly depends on the context and use case. 😊

@malhal
Copy link
Contributor Author

malhal commented Jan 18, 2025

Yes you're right, e.g. for a top level model object, you can do a fileprivate letoutside of the app struct. In Swift globals are lazy and if you use it from body then that gives the same semantics as StateObject without needing ObservableObject for your @Observableclass, e.g.

fileprivate let model = Model() // @Observable class

struct App: App {
   var body: some Scene
       ...
       .environment(model) // model is init here once.
   }
}

Downside is the model can't be re-init.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants