IceCubesApp icon indicating copy to clipboard operation
IceCubesApp copied to clipboard

Bug/Discussion: ViewModels are initialised multiple times?

Open theedov opened this issue 1 year ago • 7 comments

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 avatar Apr 23 '24 01:04 theedov

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

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

@StateObject private var viewModel = ViewModel(()

theedov avatar Apr 25 '24 14:04 theedov

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.

Dimillian avatar Apr 25 '24 15:04 Dimillian

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

Wouter01 avatar Apr 25 '24 19:04 Wouter01

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

stonko1994 avatar Apr 26 '24 05:04 stonko1994

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 🤔

theedov avatar Apr 26 '24 06:04 theedov

Do you see that in the memory graph?

Dimillian avatar Apr 26 '24 07:04 Dimillian

Think so. image

theedov avatar Apr 27 '24 10:04 theedov