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

Bug/Discussion: ViewModels are initialised multiple times? #2033

Open
theedov opened this issue Apr 23, 2024 · 7 comments
Open

Bug/Discussion: ViewModels are initialised multiple times? #2033

theedov opened this issue Apr 23, 2024 · 7 comments
Labels
bug Something isn't working

Comments

@theedov
Copy link

theedov commented Apr 23, 2024

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

@theedov theedov added the bug Something isn't working label Apr 23, 2024
@theedov
Copy link
Author

theedov commented Apr 25, 2024

Another potential option is to conform viewmodel to ObservableObject and keep using @StateObject.

@Observable
final class ViewModel: ObservableObject {
....
}

@StateObject private var viewModel = ViewModel(()

@Dimillian
Copy link
Owner

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.

@Wouter01
Copy link

You can fix this by using a custom property wrapper instead of @State: https://hachyderm.io/@groue/112320663017999822

@stonko1994
Copy link

Maybe switching to this approach would help: https://stackoverflow.com/a/71010187/2307466 🤔

@theedov
Copy link
Author

theedov commented Apr 26, 2024

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.

It creates multiple instances of the same VM and doesn't seem to deinitialize all of the "redundant" ones though 🤔

@Dimillian
Copy link
Owner

Do you see that in the memory graph?

@theedov
Copy link
Author

theedov commented Apr 27, 2024

Think so.
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants