Persist SwiftUI State With Observations

An autosave system needs to remember where you ended up. It does not necessarily need a stenographer for every keystroke.

Suppose a library screen keeps a search query and a favorites filter in an @Observable model. We want to restore those settings next time, save changes while the screen is open, and report whether the current settings have actually been written.

Observations gives us an async sequence of computed state from observable properties. It arrived with Swift 6.2 and iOS 26/macOS 26; it remains useful in an Xcode 27 project today. The complete example below was compiled with the installed Swift 6.4 toolchain.

Use Your Loaf’s scene-state article demonstrates the basic connection. We’ll build on that idea with a small file store, explicit failures, and a save receipt. Older questions about continuous observation already have workarounds; the opportunity here is a clearer end-to-end contract.

Observe a consistent value

The closure passed to Observations reads the properties that matter and returns a value snapshot. Create it on the main actor when those properties belong to a main-actor model.

Related synchronous mutations can produce one consistent snapshot. A slower consumer can skip intermediate states. That makes this API useful for restoring the latest filter configuration, but unsuitable for recording every edit or business event. Transactional observation also isn’t a timed debounce: it does not promise a 300-millisecond pause between disk writes. SE-0475 defines those observation semantics.

This sample can write once per typed character. For a busy editor, add a measured debounce or another write-budget policy while preserving the direct flush() path below.

The first iteration reads the current value. That gives us two rules: restore before observing, and don’t blindly discard the first emission. Someone may already have edited the restored settings before the observer begins.

Give persistence a small contract

Our atomic document-saving article covers the underlying write policy. We’ll reuse that approach here, adding a restored snapshot and a receipt containing the highest successfully saved revision.

Put the following four Swift blocks in one file. This first block contains the value type, a storage interface for testing, and a small app-owned JSON store:

import Foundation
import Observation

nonisolated struct FilterSnapshot: Codable, Sendable, Equatable {
    let version: Int
    let revision: UInt64
    let query: String
    let favoritesOnly: Bool

    static let empty = FilterSnapshot(
        version: 1, revision: 0, query: "", favoritesOnly: false
    )
}

nonisolated protocol FilterStorage: Sendable {
    func load() async throws -> FilterSnapshot?
    func save(_ snapshot: FilterSnapshot) async throws -> UInt64
}

actor FilterFile: FilterStorage {
    private let url: URL
    private var savedRevision: UInt64?

    init(url: URL) { self.url = url }

    func load() throws -> FilterSnapshot? {
        let data: Data
        do { data = try Data(contentsOf: url) }
        catch CocoaError.fileReadNoSuchFile { return nil }

        let snapshot = try JSONDecoder().decode(FilterSnapshot.self, from: data)
        guard snapshot.version == 1 else {
            throw CocoaError(.coderReadCorrupt)
        }
        savedRevision = snapshot.revision
        return snapshot
    }

    func save(_ snapshot: FilterSnapshot) throws -> UInt64 {
        if let savedRevision, snapshot.revision <= savedRevision {
            return savedRevision
        }
        let data = try JSONEncoder().encode(snapshot)
        try FileManager.default.createDirectory(
            at: url.deletingLastPathComponent(),
            withIntermediateDirectories: true
        )
        try data.write(to: url, options: .atomic)
        savedRevision = snapshot.revision
        return snapshot.revision
    }
}

The revision travels with its query and filter. It comes from the state owner, so a late autosave cannot invent a newer revision just because it arrived later.

FilterFile.save has no suspension between checking the revision and completing the write. An actor serializes access, but it does not promise FIFO ordering across independent tasks; the actors proposal makes that distinction explicit. The revision guard is what stops an older observation from replacing a newer manual save.

The receipt advances only after success. A failed write can therefore retry the same revision. Equal or older revisions return the existing receipt without another write. Apple’s atomic writing option writes an auxiliary file before replacing the destination; that is separate from our ordering policy.

Only a missing file selects fresh defaults. A decoding error, an unsupported format version, or another read error escapes load(). Do not turn those cases into a blank model that immediately autosaves over the evidence. Our Codable format-versioning article covers a fuller migration policy.

This synchronous file work runs on the storage actor, away from the UI’s actor. It still occupies an executor thread while running; an actor is not a dedicated I/O thread. Keep this approach for small, infrequent state snapshots. Large documents, high-frequency edits, shared files, and coordinated multi-file writes need a storage design suited to that workload.

Track what was saved, not just what was attempted

The session owns the editable settings and their revision. It also owns save status, but the observation closure reads only the persisted snapshot:

@available(iOS 26.0, macOS 26.0, *)
@Observable @MainActor
final class FilterSession {
    var query: String { didSet { revision += 1 } }
    var favoritesOnly: Bool { didSet { revision += 1 } }
    private(set) var revision: UInt64
    private(set) var savedRevision: UInt64?
    private(set) var saveError: String?

    @ObservationIgnored private var failedRevision: UInt64?
    private let storage: any FilterStorage

    var snapshot: FilterSnapshot {
        FilterSnapshot(
            version: 1, revision: revision,
            query: query, favoritesOnly: favoritesOnly
        )
    }

    var isSaved: Bool { savedRevision == revision }

    private init(storage: any FilterStorage, restored: FilterSnapshot?) {
        let initial = restored ?? .empty
        self.storage = storage
        query = initial.query
        favoritesOnly = initial.favoritesOnly
        revision = initial.revision
        savedRevision = restored?.revision
    }

    static func open(using storage: any FilterStorage) async throws -> FilterSession {
        let restored = try await storage.load()
        try Task.checkCancellation()
        return FilterSession(storage: storage, restored: restored)
    }

    func observeChanges() async {
        let values = Observations { self.snapshot }
        for await value in values {
            guard !Task.isCancelled else { return }
            _ = await persist(value)
        }
    }

    @discardableResult
    func flush() async -> Bool {
        let current = snapshot
        return await persist(current)
    }

    private func persist(_ value: FilterSnapshot) async -> Bool {
        do {
            let receipt = try await storage.save(value)
            savedRevision = max(savedRevision ?? receipt, receipt)
            if let failedRevision, let savedRevision,
                failedRevision <= savedRevision {
                self.failedRevision = nil
                saveError = nil
            }
            return true
        } catch {
            let alreadySaved = savedRevision.map { $0 >= value.revision } ?? false
            if !alreadySaved,
                failedRevision.map({ value.revision >= $0 }) ?? true {
                failedRevision = value.revision
                saveError = "Couldn't save changes: \(error.localizedDescription)"
            }
            return false
        }
    }
}

There are three useful details in this loop.

First, it awaits each save. It does not create a separate unstructured task for every emitted value. If storage is busy, the sequence can coalesce state changes while this consumer is waiting.

Second, saveError and savedRevision are absent from snapshot. Updating a save indicator should not trigger another save and turn the status label into a tiny perpetual-motion machine.

Third, a save receipt and the current revision answer different questions. If revision 8 finishes while the user is editing revision 9, isSaved stays false. Taking the maximum receipt also prevents a delayed older completion from moving the indicator backward. A failure for an already acknowledged revision does not replace a newer successful status.

The two didSet observers advance the revision whenever a setting is assigned. Keep future persisted fields in this same snapshot and revision policy. Reuse one session and one writer for a destination; independent editors cannot safely share a revision counter merely because they share a filename.

Make saving on demand independent of observation delivery

flush() captures the current snapshot directly, then awaits the storage result. It doesn’t wait for an observation callback to deliver the last edit.

Its success means that the captured revision, or a later revision from this owner, has been persisted. It does not mean the screen will still be clean when the method returns: editing can continue during the await. The isSaved comparison expresses that distinction in the UI.

A failed observation save leaves the loop available for future changes, but there might not be another change. The user needs a retry path. These controls expose one:

import SwiftUI

@available(iOS 26.0, macOS 26.0, *)
@MainActor
struct FilterControls: View {
    @Bindable var session: FilterSession
    @State private var saveRequest = 0

    var body: some View {
        Form {
            TextField("Search", text: $session.query)
            Toggle("Favorites only", isOn: $session.favoritesOnly)
            Text(session.isSaved ? "Saved" : "Changes not yet saved")
            if let error = session.saveError {
                Text(error).foregroundStyle(.red)
            }
            Button("Save now") { saveRequest += 1 }
        }
        .task { await session.observeChanges() }
        .task(id: saveRequest) {
            guard saveRequest > 0 else { return }
            await session.flush()
        }
    }
}

The ordinary .task owns the observation loop. The second task runs an explicit save when the button changes its request value. SwiftUI cancels view tasks when their view lifetime ends; see Apple’s task modifier. A synchronous write already underway may still complete, and its receipt remains useful.

If this screen reappears, the new observation iteration starts from current state. We don’t use a Boolean guard that might reject the new observer while an older cancelled task is still returning from a save.

For an app-controlled Done action, await flush() before dismissing. If success must cover the very last edit, disable editing during that operation and dismiss only after it succeeds. Merely launching a save task and immediately closing the editor does not establish that checkpoint.

Restore before making the controls editable

Here is a complete host view. Use FilterDemo() in a single-window sample with an iOS 26/macOS 26 deployment target, or behind an availability check:

@available(iOS 26.0, macOS 26.0, *)
@MainActor
struct FilterDemo: View {
    @State private var session: FilterSession?
    @State private var loadError: String?
    @State private var loadRequest = 0

    var body: some View {
        NavigationStack {
            Group {
                if let session {
                    FilterControls(session: session)
                } else if let loadError {
                    ContentUnavailableView {
                        Label("Settings couldn't open", systemImage: "exclamationmark.triangle")
                    } description: {
                        Text(loadError)
                    } actions: {
                        Button("Try again") { loadRequest += 1 }
                    }
                } else {
                    ProgressView("Opening settings…")
                }
            }
            .navigationTitle("Library filters")
        }
        .task(id: loadRequest) {
            guard session == nil else { return }
            loadError = nil
            do {
                let url = URL.applicationSupportDirectory
                    .appending(path: "FilterDemo/preferences.json")
                let restored = try await FilterSession.open(using: FilterFile(url: url))
                try Task.checkCancellation()
                session = restored
            } catch {
                guard !Task.isCancelled else { return }
                loadError = error.localizedDescription
            }
        }
    }
}

The host does not create FilterControls until loading succeeds. A corrupt file therefore produces an error screen with no observation loop waiting to overwrite it. Retrying attempts the read again; it does not delete the file or reset the settings.

The load task sits on the stable navigation container, outside the loading/error/content branches. The extra cancellation check prevents an abandoned load from installing its result.

The example’s fixed Application Support path is for one state owner. For multiple independent scenes, give each a stable, separate destination; for shared settings, inject the same session rather than opening this file independently in each window. Do not attach this writer to a file already managed by DocumentGroup or another document system.

Treat the last save as a requirement you own

Observation reduces the window of unsaved state while the app is running. It cannot promise to persist a change after the process has been terminated, and cancelling an iterator is not a final flush.

You can request another checkpoint when a scene becomes inactive or enters the background, but that is an additional opportunity, not guaranteed execution time. Apple’s scene phase guidance says to expect termination after entering the background. For an app-controlled workflow, save before the transition. For critical data, choose a persistence policy that matches the acceptable loss window instead of relying on a final lifecycle callback.

If you add a timed debounce, keep flush() as a direct path to the current snapshot. Waiting for the debounce timer to expire is not an explicit save operation.

Verify the boundaries

The verification checks use the exact published code, a real temporary file, and a controlled storage implementation. They verify the initial observation value, combined synchronous changes, slow-consumer coalescing, cancellation, restoration, and preservation of corrupt or unsupported files. They also hold a save pending while newer settings arrive, reorder receipts, fail a write, retry without another edit, and flush before starting observation.

Verified October 2, 2026: all four Swift blocks compile for iOS 26 and macOS 26 with Xcode 27.0 / Swift 6.4, in Swift 6 mode with warnings as errors. Both ordinary isolation and MainActor default isolation are checked. The model, observation, and file checks run on the installed Mac. Device lifecycle timing, accessibility, and power-loss durability remain separate integration tests.