With the new @Observable macro, it looks like every time the struct of a view is reinitialized, any observable class marked as @State in the struct also gets reinitialized. Moreover, the result of the reinitialization immediately gets discarded.
This is in contrast to @StateObject and ObservableObject, where the class would only be initialized at the first creation of the view. The initialization method of the class would never be called again between view updates.
Is this a bug or an expected behavior? This redundant reinitialization causes performance issues when the init method of the observable class does anything slightly heavyweight.
Feedback ID: FB13697724
Hi @NSCruiser,
Please see the WWDC23 session, titled, Discover Observation in SwiftUI, which states:
When the view needs to have its own state stored in a model, use the
@State
property. Here we have the observable model object Donut being used in a sheet presentation. When the sheet is presented, thedonutToAdd
state variable is used to bind values to the editable fields. ThedonutToAdd
property is managed by the lifetime of the view it's contained in.
The behavior you report is likely a bug on iOS 17.4 Seed 3 (21E5200d). Please attempt to reproduce the issue on iOS 17.6 Release Candidate (21G79) or iOS 18 beta 4 (22A5316k) and update your existing Feedback (FB13697724) with the results.
Cheers,
Paris