Search code examples
swiftuistateobservableobjectobservedobject

Assigning an ObservedState’s published value to a state


I have a state called time

@State var time = 0

and an ObservedObject called timerWrapper

@ObservedObject var timerWrapper = TimerWrapper()

time can be updated from a child view and I want to be also able to update it using the timerWrapper (theObservedObject), if I use this:

self.time = self.timerWrapper.remainingSeconds

and do this:

Text($time)

The text doesn’t update. It only works if I do this:

Text(self.timerWrapper.remainingSeconds)

I know that’s because when remainingSeconds is published it will reload the UI. But how can I get around this? Reminder I have 2 possible sources that can updated time, this is why I’m not using the observed object directly when creating the Text in the viewbuilder.


Solution

  • If you want to update local state on view model published property (for whatever reason), here is a way to do this

    Text(time)   // << not binding, just property
       .onReceive(timerWrapper.$remainingSeconds) { value in // listen for publisher $
          self.time = value
       }