Learn how to migrate from legacy live query APIs to store observers with the new Differ
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.
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.
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.
Copy
Ask AI
let differ = DittoDiffer()var previousDocumentIds: [String] = [] // Store only extracted IDslet observer = ditto.store.registerObserver( query: "SELECT * FROM cars") { queryResult in let diff = differ.diff(queryResult.items) // Extract current document IDs and dematerialize items let currentDocumentIds = queryResult.items.map { item in let id = item.value["_id"] as? String ?? "unknown" item.dematerialize() // Release memory after extracting data return id } // Handle deletions using stored IDs from previous emission for index in diff.deletions { let deletedId = previousDocumentIds[index] print("Deleted car with ID: \(deletedId)") } // Handle insertions using current IDs for index in diff.insertions { let insertedId = currentDocumentIds[index] print("Inserted car with ID: \(insertedId)") } // Handle updates using current IDs for index in diff.updates { let updatedId = currentDocumentIds[index] print("Updated car with ID: \(updatedId)") } // Store only the document IDs for next callback - no live references! previousDocumentIds = currentDocumentIds}