@published var not updating view

Got a frustrating problem. I've created two separate views (and view models) for my app, one to use in portrait mode, the other to take advantage of the extra horizontal space in landscape. In both view models, I have a bool called usingClock.

  @Published var usingClock: Bool = false

and in my view, I set the opacity of this clock depending on this bool...

Text(vm.isRunning ? vm.formatTime() : "0")
              .font(.system(.title2, design: .monospaced))
              .fontWeight(.black)
              .frame(width: 90, height: 40)
              .background(.thinMaterial)
              .cornerRadius(20)
              .overlay(RoundedRectangle(cornerRadius: 20)
                    .stroke(Color.gray, lineWidth: 2))
              .opacity(vm.usingClock ? 1.00 : 0.00)

what is crazy is that in my portrait mode, this works. I change the setting of the bool, and the view automatically updates. but in the landscape mode, it doesn't work. I change the setting of the bool, and the view does not update. but if I simply re-orient the phone (simulator) to portrait and then back to landscape, now the view is correct. I can't for the life of me figure out why the exact same code works in portrait mode, regardless of me changing the orientation, and why in landscape mode it doesn't work until I rotate the phone.

I've even placed print statements showing that in my view model the bool turns false (say) and then in my view, it prints as true. Then simply reorient the phone, and now both print statements are false. Like what????

Any ideas why this is happening? This code is not that complicated.

Answered by maark6000 in 723654022

Ah I figured it out. Man, I always do this. I declare two @StateObjects of the same view model. I forget that you can only declare ONE @StateObject view model, and then any time you need to reference it you must use @ObservedObject var myViewModel: MyViewModel. And notice, not MyViewModel(). And then you have to try to figure out how to make the preview happy, which is not easy.

Accepted Answer

Ah I figured it out. Man, I always do this. I declare two @StateObjects of the same view model. I forget that you can only declare ONE @StateObject view model, and then any time you need to reference it you must use @ObservedObject var myViewModel: MyViewModel. And notice, not MyViewModel(). And then you have to try to figure out how to make the preview happy, which is not easy.

@published var not updating view
 
 
Q