Swift Observations AsyncSequen... Note

Swift Observations AsyncSequence for State Changes

Swift 6.2 introduces a new Observations type to stream state changes from Observable types. This is useful for persisting application state, like a scene's search query and navigation path. The author previously managed this state in a Codable class, SceneModel, which could be encoded to JSON for persistence.This SceneModel was then saved and restored using @SceneStorage in the root view. However, saving state relied on monitoring the scenePhase, which was unreliable as scenes might terminate before entering the background. Before Swift 6.2, ObservableObject with @Published properties allowed using Combine's buffer and values to create an AsyncSequence for saving state changes.With iOS 26 and Swift 6.2, the Observations type provides a similar AsyncSequence for Observable types. This allows observing computed properties, such as the JSON representation of the SceneModel. The Observations type takes a closure that returns the value to be observed.Changes are transactional, meaning multiple synchronous updates to observable properties are batched into a single sequence value. The tracking of updates starts with the willSet of observable properties and concludes at the next suspension point. This enables saving the scene model’s state automatically whenever it changes, without relying on scenePhase. The AsyncSequence from Observations emits the initial value of the observed property upon subscription.