Skip to main content
You can react to changes in your local store by setting up a store observer. You can read more about store observers in Accessing Data. Store observers are useful when you want to monitor changes from your local Ditto store and react to them immediately. For instance, when your end user updates their profile, asynchronously display changes in realtime.

Local Writes and Observer Delivery

A local write may not be delivered to store observers before the write operation returns. Callers should assume it will not be. Do not rely on state populated by observer callbacks including a local write immediately after execute returns. If your code needs the current data right after a write, read it from the store directly or wait for the observer callback instead of assuming the write has already been delivered.

Setting Up Store Observers

Using the registerObserver method, set up an observer within the store namespace enclosed with a query that specifies the collection to watch for changes, as well as your logic to handle the incoming changes.
A Store Observer DQL statement is only triggered when the Store Observer is created and when data in the collection changes[1].Do not expect use of a non-deterministic function such as clock() in the DQL statement will alone result in additional invocations as time passes.[1] There is a special case for some system virtual collections; see Timer driven observers.Store observer
Observer results are snapshots: several writes can be combined into one delivery, so they are not a log of every write.

Basic Query Observer in JavaScript and TypeScript

This example is currently available for JavaScript and TypeScript. The query arguments example below covers every SDK. The JavaScript and TypeScript examples below receive the initial query result and subsequent changed results. Copy the values needed by your application and dematerialize() each item after reading it. The stopped flag is used when canceling the observer.
In JavaScript and TypeScript, registerObserver releases backpressure when your handler returns; it does not await a returned promise. For asynchronous processing with backpressure, use registerObserverWithSignalNext and call the supplied signalNext() when processing is complete. While delivery is paused, changes are combined into the latest result, so copy the values you need before keeping data for asynchronous work.

Store Observer with Query Arguments

To associate arguments with your query add them as a parameter.

Canceling a Store Observer

To cancel a store observer, call cancel() on the observer object (close() in Kotlin and Java, Cancel() in C# and Go). Once canceled, the store observer stops processing in the background and is not called for later changes. Depending on timing, a callback that was already queued when you canceled may still run.
In JavaScript and TypeScript, the initial callback can run after cancel() returns, even though isCancelled is already true. The JS/TS examples set an application-owned stopped flag when they cancel, and the handler checks it before doing any work. Cancellation does not undo work a handler has already started, so asynchronous handlers should also check the flag after each await.

Accessing Store Observers

To access store observers from the local Ditto store:

Diffing Results

This feature is available in v4.11 and above.
There are some use cases where it may be required to calculate the difference between previous and current query results. For example, when you want to update a UI component or external HTTP system with the latest data, you may want to know which items have been added, removed, or changed since the last time you received the query result. The Ditto SDK provides a DittoDiffer class that allows you to opt-in to diffing only when necessary, thereby avoiding unnecessary performance and memory costs. However, diffing is computationally expensive. It requires storing the previous query results in memory, leading to increased RAM usage, which can be particularly problematic for applications handling large datasets or frequent updates. Instead of computing diffs synchronously with every store observer update, it is recommended to debounce diffing, processing changes out-of-band at a cadence that best suits your use case.
Critical Memory Management: QueryResults and QueryResultItems should be treated like database cursors. Always extract the data you need immediately and then close/dematerialize them. Never store QueryResultItems directly between observer emissions as this will cause memory bloat and potential crashes.
A DittoDiffer (Differ in JS/TS) is given query result items and compares them to the previous set of items it has received. The JS/TS examples use ORDER BY to define result order, preserve the original IDs (including composite IDs), and handle moves as well as insertions, updates, and deletions. Deletion indices refer to the previous result; insertion and update indices refer to the current result. Each move has from in the previous result and to in the current result. Only extracted IDs are retained by application code between callbacks: Run the Swift example inside an async throws function. To start it from SwiftUI’s .task modifier, wrap it in do { ... } catch { ... }, because the .task closure can’t throw. Cancelling the task ends the loop and cancels the observer through the stream’s onTermination cleanup. handlerWithSignalNext makes Ditto wait for signalNext() after each result is processed, so only one result is handled at a time; changes made while waiting may arrive together in the next result.
The diff() method returns a DittoDiff containing:
  • insertions: Indexes of new items in the new array
  • deletions: Indexes of items that were removed from the old array
  • updates: Indexes of items in the new array that were present in the old array and whose value has changed
  • moves: Pairs of indexes showing items that changed position

Key considerations

  • Keep references to arrays yourself: The differ doesn’t provide access to the old and new items themselves, so they need to be retained by the user if needed.
  • No comparison of document metadata: The differ performs a deep comparison of the value of each query result item but doesn’t take into account any metadata. Applying a series of changes to a document will not cause it to show up in updated unless those changes result in a different value from the initial state to the final state.
  • No async diffing: Computing a diff on a set of many query result items or very large query result items might block the device depending on its hardware.

Migrating from Live Query Events

If you’re using the legacy live query API that automatically provides diff information through event parameters, you can migrate to the newer store observer pattern with the DittoDiffer class. The differ provides equivalent functionality but requires manual management of previous results. For a complete migration guide, see Replacing Live Query Events with Store Observers.

Updating a SwiftUI View

Use BlueCarsView(ditto: ditto) with an initialized Ditto instance to display blue cars in SwiftUI. SwiftUI reconciles rows by their IDs, so this example does not need the separate DittoDiffer example above. The example supports macOS 12 and iOS 15 or later. It bridges the observer into an AsyncSequence, decoding copied values on a background queue. bufferingNewest(1) keeps the latest snapshot if the UI falls behind. One loop in the @MainActor model updates UI state safely. SwiftUI’s .task starts observation and cancels it when the view disappears; stream termination cancels the observer. A snapshot that fails to decode shows an error without ending observation, and the next valid snapshot clears the error.