skip to content

Outside SwiftUI views, how do you react to changes in an @Observable model with withObservationTracking or the Observations sequence, and what catches people out?

level: seniorimportance: should knowfreq 30%

answer

  1. the same tracking body uses
  2. one shot, then re-register
  3. fires before the new value lands
  4. an async sequence on iOS 26

basics

~20 s

withObservationTracking(_:onChange:) runs a closure, records the observable properties it reads, and calls onChange once, before the first of them changes; you must re-register to keep watching. On iOS 26 and later, Observations wraps this as an async sequence.

solid answer

~50 s

`withObservationTracking(_:onChange:)` from the Observation framework is the primitive SwiftUI's own `body` tracking mirrors: the `apply` closure's reads decide what is watched. Three things catch people out. It is **one-shot**: after the first change `onChange` is not called again, so you re-run the tracking to keep observing. It fires in **willSet**, so the property still holds the old value inside `onChange`; you schedule work rather than read the new value there. And `onChange` is `@Sendable` and runs on whichever thread made the change. On iOS 26, `Observations { cart.items.count }` packages this as an `AsyncSequence`: it yields the current value first, then a new value after changes, coalescing synchronous mutations into one element. I use these to sync a cart to storage or feed a UIKit screen, never inside a SwiftUI view, which tracks its `body` reads already.

code

swift · 24 lines
swift
import Observation

@MainActor
final class CartSync {
    private let cart: CartModel
    init(cart: CartModel) { self.cart = cart }

    func observe() {
        let count = withObservationTracking {
            cart.items.count
        } onChange: { [weak self] in
            // Called once, before items changes: it still holds the old value.
            Task { @MainActor in self?.observe() }   // re-register
        }
        print("Cart has \(count) items")
    }

    @available(iOS 26, *)
    func streamCounts() async {
        for await count in Observations({ self.cart.items.count }) {
            print("Cart now has \(count) items")
        }
    }
}

go deeper

for a junior

Know that code outside views can watch an @Observable model, and that SwiftUI views already do this for their body.

for a middle

Explain the apply and onChange closures, and why only properties read in apply are watched.

for a senior

Handle the traps in production code: one-shot re-registration, will-set timing, threads and Sendable, and availability for Observations.

for a principal

Decide where non-UI reactions to model changes live (persistence, analytics, UIKit bridges) so each model has one observer, not scattered callbacks.

## Why you would observe outside a view Inside SwiftUI, nothing extra is needed: each view forms dependencies on the properties its `body` reads, and is updated when one of them changes. Outside views there is no `body`, yet code still needs to react to an `@Observable` model. Typical cases in a shop app: - saving the cart to disk or a server when `items` changes; - sending an analytics event when checkout starts; - updating a UIKit screen or a widget timeline that shares the model; - keeping a derived value in another object in step with the cart. The **Observation** framework offers two public tools for this, plus newer variants in iOS 27. ## withObservationTracking: the one-shot primitive **`withObservationTracking(_:onChange:)`** (iOS 17) takes two closures. The `apply` closure runs immediately, and every tracked property it reads is recorded. The `onChange` closure is called when one of those properties is about to change. Apple's example tracks `car.name` and is not called when `needsRepairs` changes, because `apply` never read it. Three details trip people up: 1. **It fires once.** In the Swift 6.4 Observation source, the tracking is cancelled right after `onChange` is called, so later changes are not reported. To keep observing, start tracking again, usually by scheduling a re-run from `onChange`. 2. **It fires in willSet.** The callback is installed on the will-set side of the mutation, so inside `onChange` the property still holds its old value. Read the new value on the next run of `apply`, not in the callback. 3. **It runs where the mutation runs.** The callback is called synchronously from the thread or actor that performed the write. That is why it is `@Sendable`, and why UI work in it should hop to the main actor. ## Observations: an async sequence (iOS 26) **`Observations`** wraps the same idea as an `AsyncSequence`. Its initializer takes a closure that extracts a value from one or more observable objects: | Behaviour | What happens | |---|---| | First call to `next()` | runs the closure and yields the current value at once | | Later calls | wait for the will-set of a change, then re-run the closure | | Several synchronous writes | coalesced; Apple describes the boundary as running from the first mutation's will-set to the next suspension point | | Ending | cancel the task that iterates it, or use `untilFinished(_:)` and return `.finish` | Because it re-runs the closure after each change, it re-registers by itself, which removes the one-shot trap. The element type must be `Sendable`, and the closure inherits the actor context it is created in, so creating it on the main actor keeps a main-actor model safe to read. ## iOS 27 additions The iOS 27 SDK adds **`withObservationTracking(options:_:onChange:)`**, whose options choose `willSet`, `didSet` or `deinit` events and whose callback receives an event describing its kind, and **`withContinuousObservation(options:apply:)`**, which keeps observing and returns a token you cancel. Apps that still deploy to iOS 17 or 18 need the original function or an availability check. ## Mistakes to avoid - Expecting `onChange` to fire for every change and losing every update after the first. - Reading the model inside `onChange` and saving the old value. - Touching UIKit from `onChange` without hopping to the main actor. - Wrapping a SwiftUI view's reads in `withObservationTracking`: views already track their `body`. - Shipping `Observations` in an app that deploys below iOS 26 without an `if #available` check. ## Choosing between them - Deploying to iOS 17 or 18: `withObservationTracking(_:onChange:)` with explicit re-registration, wrapped in one small helper so the traps are handled once. - Deploying to iOS 26 or later: `Observations` in a `Task` tied to the owner's lifetime, cancelled when the owner goes away. - Needing did-set timing or continuous callbacks on iOS 27: the options-based variants. - Inside a SwiftUI view: neither; read the property in `body`, and use `onChange(of:initial:_:)` for side effects there. Combine's publishers are the older way to stream changes and belong with Combine; this leaf is about Observation's own tools.

  • Why does reading cart.items inside onChange give the value before the change?
    `withObservationTracking(_:onChange:)` installs its callback on the will-set side of the mutation, so it runs before the new value is stored. Use the callback to schedule a new tracking pass, and read the value when `apply` runs again.
  • If code appends three items in one synchronous loop, how many values does an Observations sequence yield?
    Typically one. `Observations` waits for the first will-set, then re-runs its closure after the next suspension point, so writes made together without suspending are seen as one transaction and yield a single new count.

  • withObservationTracking calls onChange for every later change automatically
  • onChange receives the new value or can read it from the model
  • onChange always runs on the main thread
  • Observations works on any iOS release that supports @Observable
  • SwiftUI views need withObservationTracking to see model changes

withObservationTracking(_:onChange:) dates from iOS 17; the Observations sequence needs iOS 26, and iOS 27 adds withObservationTracking(options:_:onChange:) and withContinuousObservation(options:apply:).