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
Bug/Discussion: ViewModels are initialised multiple times? #2033
Comments
Another potential option is to conform viewmodel to ObservableObject and keep using @StateObject.
|
FYI, I hear you, and I know the issue is there, but the workaround is just ugly. As I mostly don't do anything in my Observable init I don't really care. This doesn't create an issue as of today for me in this app. |
You can fix this by using a custom property wrapper instead of |
Maybe switching to this approach would help: https://stackoverflow.com/a/71010187/2307466 🤔 |
It creates multiple instances of the same VM and doesn't seem to deinitialize all of the "redundant" ones though 🤔 |
Do you see that in the memory graph? |
I'm not sure if this is a bug tbh but I've noticed that @observable objects are being initialised multiple times.
So this
@State private var viewModel = TimelineViewModel()
for example would call TimelineViewModel.init multiple times.Here is a forum post I could find about this "issue" https://forums.swift.org/t/observable-init-called-multiple-times-by-state-different-behavior-to-stateobject/70811/8
Apple also suggests initialising objects inside
.task
which would leave us with optionals everywhere...https://developer.apple.com/documentation/swiftui/state#Store-observable-objects
The text was updated successfully, but these errors were encountered: