Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
SDK de C++

React a cambios - C++ SDK

All Realm objects are live objects, which means they automatically update whenever they're modified. Realm emits a notification event whenever any property changes. You can register a notification handler to listen for these notification events, and update your UI with the latest data.

You can register a notification handler on a specific object within a realm. Realm notifies your handler:

  • Cuando el objeto se borra.

  • When any of the object's properties change.

auto token = object.observe([&](auto&& change) { ... }

El manejador recibe un Objetoobject_change que contiene información sobre los cambios, como si el objeto se eliminó. Puede incluir una lista de objetos PropertyChange que contienen información sobre los campos modificados, sus nuevos valores (excepto en las propiedades de lista) y, posiblemente, sus valores anteriores.

if (change.error) {
rethrow_exception(change.error);
}
if (change.is_deleted) {
std::cout << "The object was deleted.\n";
} else {
for (auto& propertyChange : change.property_changes) {
std::cout << "The object's " << propertyChange.name
<< " property has changed.\n";
auto newPropertyValue =
std::get<std::string>(*propertyChange.new_value);
std::cout << "The new value is " << newPropertyValue << "\n";
}
}

Cuando realice cambios, actualice() el reino para emitir una notificación.

auto config = realm::db_config();
auto realm = realm::db(std::move(config));
// Create an object and move it into the database.
auto dog = realm::Dog{.name = "Max"};
realm.write([&] { realm.add(std::move(dog)); });
auto dogs = realm.objects<realm::Dog>();
auto specificDog = dogs[0];
// Set up the listener & observe object notifications.
auto token = specificDog.observe([&](auto&& change) {
try {
if (change.error) {
rethrow_exception(change.error);
}
if (change.is_deleted) {
std::cout << "The object was deleted.\n";
} else {
for (auto& propertyChange : change.property_changes) {
std::cout << "The object's " << propertyChange.name
<< " property has changed.\n";
auto newPropertyValue =
std::get<std::string>(*propertyChange.new_value);
std::cout << "The new value is " << newPropertyValue << "\n";
}
}
} catch (std::exception const& e) {
std::cerr << "Error: " << e.what() << "\n";
}
});
// Update the dog's name to see the effect.
realm.write([&] { specificDog.name = "Wolfie"; });
// Deleting the object triggers a delete notification.
realm.write([&] { realm.remove(specificDog); });
// Refresh the database after the change to trigger the notification.
realm.refresh();
// Unregister the token when done observing.
token.unregister();

You can register a notification handler on a collection. A collection is a list, map, or set property that can contain any supported data type, including primitives or other objects.

Realm notifica a tu manejador cada vez que una transacción de escritura elimina, agrega o cambia objetos en la colección.

Notifications describe the changes since the prior notification with three lists of indices: the indices of the objects that were removed, inserted, and modified.

Importante

El orden importa

En los controladores de notificaciones de colecciones, aplique siempre los cambios en el siguiente orden: eliminaciones, inserciones y modificaciones. Gestionar las inserciones antes de las eliminaciones puede provocar un comportamiento inesperado.

Las notificaciones de colección proporcionan una estructura collection_change que informa el índice de los objetos eliminados, añadidos o modificados. También pueden notificarle si la colección se eliminó.

En este ejemplo, el Person El objeto tiene una lista de Dog objetos como propiedad:

struct Person {
std::string name;
std::vector<Dog*> dogs;
};
REALM_SCHEMA(Person, name, dogs)

Remover un perro, agregar un perro nuevo o modificar un perro activar el manejador de notificaciones:

// Set up the listener & observe a collection.
auto token = person.dogs.observe([&](auto&& changes) {
if (changes.collection_root_was_deleted) {
std::cout << "The collection was deleted.\n";
} else {
// Handle deletions, then insertions, then modifications.
for (auto& collectionChange : changes.deletions) {
std::cout << "The object at index " << std::to_string(collectionChange)
<< " was removed\n";
}
for (auto& collectionChange : changes.insertions) {
std::cout << "The object at index " << std::to_string(collectionChange)
<< " was inserted\n";
}
for (auto& collectionChange : changes.modifications) {
std::cout << "The object at index " << std::to_string(collectionChange)
<< " was modified\n";
}
}
});
// Remove an object from the collection, and then add an object to see
// deletions and insertions.
realm.write([&] {
person.dogs.clear();
person.dogs.push_back(&dog2);
});
// Modify an object to see a modification.
realm.write([&] { dog2.age = 2; });
// Refresh the realm after the change to trigger the notification.
realm.refresh();
// Unregister the token when done observing.
token.unregister();

Puede registrar un gestor de notificaciones en una colección de resultados.

Realm notifica a tu manejador cada vez que una transacción de escritura elimina, agrega o cambia objetos en la colección.

Las notificaciones describen los cambios desde la notificación anterior con tres listas de índices: los índices de los objetos que se eliminaron, insertaron o modificaron.

Importante

El orden importa

En los controladores de notificaciones de colecciones, aplique siempre los cambios en el siguiente orden: eliminaciones, inserciones y modificaciones. Gestionar las inserciones antes de las eliminaciones puede provocar un comportamiento inesperado.

Las notificaciones de recolección de resultados proporcionan una results_change struct que reporta el índice de los objetos que se borran, se agregan o se modifican. También puede avisarte si la colección fue borrada.

// Get a results collection to observe
auto dogs = realm.objects<realm::Dog>();
// Set up the listener & observe results notifications.
auto token = dogs.observe([&](auto&& changes) {
try {
if (changes.collection_root_was_deleted) {
std::cout << "The collection was deleted.\n";
} else {
// Handle deletions, then insertions, then modifications.
for (auto& resultsChange : changes.deletions) {
std::cout << "The object at index " << std::to_string(resultsChange)
<< " was deleted\n";
}
for (auto& resultsChange : changes.insertions) {
std::cout << "The object at index " << std::to_string(resultsChange)
<< " was inserted\n";
}
for (auto& resultsChange : changes.modifications) {
std::cout << "The object at index " << std::to_string(resultsChange)
<< " was modified\n";
}
}
} catch (std::exception const& e) {
std::cerr << "Error: " << e.what() << "\n";
}
});
// Delete and then add an object to see deletions and insertions.
realm.write([&] {
realm.remove(firstDog);
realm.add(std::move(dog2));
});
// Modify an object to see a modification.
realm.write([&] { dog2.age = 2; });
// Refresh the database after the change to trigger the notification.
realm.refresh();
// Unregister the token when done observing.
token.unregister();

Observation stops when the token returned by an observe call becomes invalid. You can explicitly invalidate a token by calling its unregister() member function.

// Unregister the token when done observing.
token.unregister();

Importante

Retener tokens tanto tiempo como quieras observar

Notifications stop when the token's destructor is called. For example, if the token is in a local variable that goes out of scope. You can use std::move to transfer the token to a variable in a different scope.

Changes in nested documents deeper than four levels down do not trigger change notifications.

If you have a data structure where you need to listen for changes five levels down or deeper, workarounds include:

  • Refactorice el esquema para reducir la anidación.

  • Add something like "push-to-refresh" to enable users to manually refresh data.

Volver

Enhebrado

En esta página