Observation framework came out along with iOS 17 in 2023. Using this framework, we can make objects observable very easily. Please refer to @Observable macro inย SwiftUI for quick recap if needed. It also has a function withObservationTracking(_:onChange:)
what can be used for cases where we would want to manually get a callback when a tracked property is about to change. This function works as a one shot function and the onChange
closure is called only once. Note that it is called before the value has actually changed. If we want to get the changed value, we would need to read the value on the next run loop cycle. It would be much more useful if we could use this function in a way where we could have an observation token and as long as it is set, the observation is active. Here is the function with cancellation support.
The apply closure drives which values are being tracked, and this is passed into the existing withObservationTracking(_:onChange:)
function. The token closure controls if the change should be handled and if we need to continue tracking. Will and did change are closures called before and after the value has changed.
Here is a simple example where we have a view which controls if the observation should be active or not. Changing the value in the view model only triggers the print lines when observation token is set.
If this was helpful, please let me know on Mastodon@toomasvahter orย Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.