With Ditto SDK 4.11+, the new diffing APIs can be used with store observers to produce diffs between query results in consecutive invocations. This guide explains how to use the new diffing APIs to replace usage of the legacy live query APIs.
Overview
Live queries provide their callback with an event parameter that contains a diff of the current live query event against the previous oneโa summary of which documents in the result have been:
- Inserted: Indexes of new items
- Updated: Indexes of items that existed previously, but have changed
- Deleted: Indexes of items that were removed
- Moved: Pairs of indexes showing items that changed position
Store observers donโt have a built-in feature that provides a diff, as generating it is computationally expensive. However, you can use the new Differ class to compute one when needed.
Key Differences
Legacy Live Query API
- Provides automatic diffing through the
event parameter
- Maintains
event.oldDocuments for deleted items (uses memory)
- Includes
event.isInitial flag for the first callback
- Considers metadata changes as updates
Store Observer with Differ
- Requires manual diffing using the
Differ class
- You must maintain previous results yourself
- No built-in initial event detection
- Ignores metadata-only changes when determining updates
Migration Example
Before: Using Legacy Live Query API
After: Using Store Observer with Differ
Important Memory Management: QueryResults and QueryResultItems should be treated like database cursors. Always extract the data you need and then close/dematerialize them immediately. Never store QueryResultItems directly between observer emissions.
Implementation Details
Handling Deleted and Moved Documents
With store observers, results from the previous event are no longer provided directly. You need to:
-
Store the current results at the end of each callback:
-
Use the indexes provided in
diff.deletions or diff.moves to access deleted and moved documents from your stored previousItems.
Detecting the Initial Event
The legacy APIโs event.isInitial flag isnโt available with the Differ. To detect the first callback:
In the first callback, all items passed to differ.diff show up as insertions because the differ is initially empty.
The Differ ignores metadata changes when determining updates. For example:
- Changing a document field and then setting it back to its original value will not be considered an update
- This differs from the legacy API which would count any change as an update
Generating diffs may take significant time for very large result sets. Consider whether you truly need diff information for your use case.
Interactive Example
Try the interactive example on CodePen to see both approaches in action. Open your browser console to observe the results.