Contents

HistoryObserver

Monitors a model container’s data stores for remote changes and notifies when new history transactions are available.

Declaration

final class HistoryObserver

Overview

HistoryObserver automatically listens for ModelContainer/remoteChange notifications and determines whether the incoming changes are relevant based on the models you specify at initialization. When relevant changes are detected, the observer updates its eventCounter property.

Use HistoryObserver as an @Observable object and react to changes in eventCounter from a SwiftUI view or other observer.

The observer tracks its position in each data store’s transaction history using historyTokens, enabling incremental processing of only new transactions since the last check.

You can scope the observer to specific model types using the observedModels parameter. When provided with a non-empty array, the observer filters incoming transactions to only those containing changes for the specified types (and optionally their related models). When the array is empty (the default), the observer responds to any history change in the container.

Example usage:

let observer = try HistoryObserver(
    observedModels: [Trip.self],
    modelContainer: container
)

Topics

Creating a history observer

Accessing observer properties

See Also

Data store observation