Realm objects and collections always reflect the latest state of your data when you read them. Realm emits a change notification whenever the state of your data changes, which lets you reactively update your app in response to committed write transaction.
Se pueden registrar tres tipos de listeners de notificaciones:
Un escuchador de realm se activa cada vez que cualquier objeto en un realm cambia.
Un escuchador de colección se activa cada vez que una query específica coincide con un nuevo conjunto de objetos o cuando cualquier objeto coincidente cambia.
An object listener fires whenever a specific object is deleted or has one or more properties modified.
Register a Realm Change Listener
Para registrar un detector de cambios para un reino entero, pase una función de devolución de llamada al reino MétodoaddListener(). Realm llama al oyente de forma asincrónica siempre que una operación agregue, modifique o elimine objetos en el reino.
To remove a realm listener, pass the callback to the realm's removeListener() method.
Tip
Use Object & Collection Listeners for Change Details
Realm no pasa ninguna información sobre lo que cambió a las funciones de retorno del listener de realm. Si necesitas saber más sobre qué cambió en un objeto o colección, utiliza escuchadores de objetos y escuchadores de colecciones.
Tip
Handling Exceptions Inside a Listener
Para manejar las excepciones lanzadas desde un detector de cambios, envuelva su addListener() Llamada dentro de un try...catch declaración.
// Define a listener callback function function onRealmChange() { console.log("Something changed!"); } // Add the listener callback to the realm try { realm.addListener("change", onRealmChange); } catch (error) { console.error( `An exception was thrown within the change listener: ${error}` ); } // Remember to remove the listener when you're done! realm.removeListener("change", onRealmChange);
Registrar un oyente de cambios de colección
Para registrar un detector de cambios para una colección de objetos de Realm, pase una función de devolución de llamada al método addListener() de la colección. Realm llama al detector de cambios asincrónicamente al registrarse, así como siempre que una operación añada, modifique o elimine objetos de la colección.
Para remover un oyente de colección, pase la función de retorno al método removeListener() de la colección.
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.
// You can define a listener for any collection of Realm objects const dogs = realm.objects("Dog"); // Define a listener callback function for changes to any Dog function onDogsChange(dogs, changes) { // Handle deleted Dog objects changes.deletions.forEach((index) => { // You cannot directly access deleted objects, // but you can update a UI list, etc. based on the index. console.log(`Looks like Dog #${index} has left the realm.`); }); // Handle newly added Dog objects changes.insertions.forEach((index) => { const insertedDog = dogs[index]; console.log(`Welcome our new friend, ${insertedDog.name}!`); }); // Handle Dog objects that were modified changes.modifications.forEach((index) => { const modifiedDog = dogs[index]; console.log(`Hey ${modifiedDog.name}, you look different!`); }); } // Add the listener callback to the collection of dogs try { dogs.addListener(onDogsChange); } catch (error) { console.error( `An exception was thrown within the change listener: ${error}` ); } // Remember to remove the listener when you're done! dogs.removeListener(onDogsChange);
Registrar un objeto de escucha de cambios
To register a change listener on a specific Realm object, pass a callback function to the object's addListener() method. Realm calls the listener if any of the object's properties change or if someone deletes the object.
Para remover un listener de objeto, pase la función de retorno al método del objeto removeListener().
// Define a listener callback function for changes to a specific Dog function onDogChange(dog, changes) { if (changes.deleted) { console.log(`dog is deleted: ${changes.deleted}`); } else { changes.changedProperties.forEach((prop) => { console.log(`* the value of "${prop}" changed to ${dog[prop]}`); }); } } // You can define a listener for any Realm object try { dog.addListener(onDogChange); } catch (error) { console.error( `An exception was thrown within the change listener: ${error}` ); } // Remember to remove the listeners when you're done! dog.removeListener(onDogChange);
Remove All Change Listeners
Para remover todos los listeners en un objeto Realm, objeto o instancia de colección dada, llama a la función removeAllListeners() de la instancia:
// Remove all listeners from a realm realm.removeAllListeners(); // Remove all listeners from a collection dogs.removeAllListeners(); // Remove all listeners from an object dog.removeAllListeners();
Change Notification Limits
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.