How to observe changes to properties of an @Observable from another non-view class?

I have a class A and class B, and both of them are @Observable, and none of them are a view. Class A has an instance of class B. I want to be able to listen to changes in this instance of class B, from my class A.

Previously, by using ObservableObject, instead of the @Observable macro, every property that needed to be observable, had to be declared as a Publisher. With this new framework, everything seems to be automatically synthesised, and using a Publisher is no longer required, as all the properties are observable. That being said, how can I have an equivalent using @Observable? Is this new macro only for view-facing classes?

Check out the withObservationTracking(_:onChange:) function.

It’d be cool if there were a way to turn this into an AsyncSequence of changes, roughly equivalent to Combine’s Publisher concept. Indeed, that was part of the original pitch on Swift Evolution. However, it’s trickier that you might think, and thus was deferred.

If you’re curious about the backstory, there are links to the various Swift Evolution discussion threads in the SE-0395 Observation proposal.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How to observe changes to properties of an @Observable from another non-view class?
 
 
Q