0

I have added .environmentObject(AuthViewModel()) to ContentView which is also wrapped inside geometryReader inside struct conforming to App called MyApp. Exactly like it's reccomended in this answer https://stackoverflow.com/a/71970454/14743849 .

@main
struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    var body: some Scene {
        WindowGroup {
            GeometryReader { proxy in
                       ContentView()
                           .environmentObject(AuthViewModel())
                           .environment(\.mainWindowSize, proxy.size)
                   }
        }

I started using my environment object and I have noticed that it is affecting my AuthViewModel properties by reseting their values. I think it's also worth to mention that app is not allowed to be used in landscape.

After removing geometryReader everything works fine.

burnsi
  • 6,194
  • 13
  • 17
  • 27
Dzondzula
  • 1
  • 1
  • 1
    The only safe way to initialize an observable object is with a StateObject. Don’t initialize in the body. – lorem ipsum Jan 28 '23 at 16:01
  • So if I initialize it with StateObject and then pass that to environmentObject problem i have experienced will be fixed? @loremipsum – Dzondzula Jan 28 '23 at 16:13
  • Yes it will be fixed – lorem ipsum Jan 28 '23 at 16:36
  • Each time there are changes that affect the app (say, interface orientation changes), the view hierarchy is re-rendered by calling the "body". Each time body is called, your code creates another instance of the `AuthViewModel`, effectively, resetting the data. That would be my guess why it happens. @loremipsum's suggestion is a great solution. – Baglan Jan 28 '23 at 16:48

0 Answers0