Using @StateObject to preserve the model's life cycle
Even though it has solid foundations, SwiftUI is a relatively new framework. Apple adds new features in every release to adapt to the usage done by the community of developers.
In the first release of SwiftUI, @ObservedObject
was provided to separate the model logic from the view logic. The usage that Apple was assuming was that the object would be injected from an external class, not created directly inside a View.
Creating an @ObserveObject
in a View ties the life cycle of the object to the life cycle of the view.
However, the View can be destroyed and created several times while still appearing on the screen, where it should present the content of the view. When the View is destroyed, @ObservedObject
is destroyed too, resetting its internal state.
This was a counter-intuitive behavior and most of the developers were assuming that @ObservedObject
would keep its state until the owning view was shown on the screen...