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
/ /
Sync Data

Manage Sync Subscriptions - C++ SDK

Flexible Sync uses subscriptions and permissions to determine which data to sync between your Atlas App Services App and your client device. In the client, query subscriptions manage and filter the object types that can sync to the realm.

Para usar Flexible Sync en tu aplicación, debes:

  • Configure Flexible Sync on the backend

  • Initialize the app

  • Autenticar a un usuario

  • Abra el reino sincronizado con una configuración de sincronización flexible

The setup code for the examples on this page handles these prerequisites:

// Initialize the App, authenticate a user, and open the database
auto appConfig = realm::App::configuration();
appConfig.app_id = APP_ID;
auto app = realm::App(appConfig);
auto user = app.login(realm::App::credentials::anonymous()).get();
auto syncConfig = user.flexible_sync_configuration();
auto syncedRealm = realm::db(syncConfig);

Además, los modelos utilizados con Sync deben contener una propiedad de clave principal denominada _idPara obtener más información sobre cómo definir un modelo con una clave principal, consulte Especificar una clave principal.

Your client-side subscription queries must align with the Device Sync configuration in your backend App Services App.

You subscription queries can either:

  • query todos los objetos de un tipo.

  • Query object of a type that match backend App's queryable fields.

Para obtener más información sobre cómo configurar campos consultables, consulte Campos consultables en la documentación de App Services.

A synced realm must have one or more subscriptions in order to be able to read and write data to the realm. You can only write data to the realm that matches one or more subscriptions, and matches the user's permissions. If you attempt to write objects to a realm that do not match a subscription, or for which the user does not have permission to perform the write, you get a compensating write from the server and the write reverts.

Al configurar la sincronización flexible en el backend, se especifican los campos que la aplicación cliente puede consultar. En la aplicación cliente, sync_subscription_set es una lista de cero o más objetos sync_subscription que determinan qué objetos puede almacenar el dominio.

El SDK Realm C++ también tiene un mutable_sync_subscription_set que le permite agregar, cambiar y eliminar sync_subscription objetos.

Advertencia

Query Size Limit

The size limit for any given query subscription in your subscription set is 256 kB. Exceeding this limit results in a LimitsExceeded Error.

Cuando su aplicación abra por primera vez un reino sincronizado, es posible que desee verificar que tenga la cantidad esperada de suscripciones o que tenga una suscripción específica.

Puede obtener esta información accediendo a la subscriptions() función miembro pública de un dominio. Esto proporciona el conjunto de suscripciones de sincronización, donde puede usar las size() find() funciones miembro u.

// Check the subscription count
CHECK(syncedRealm.subscriptions().size() == 1);
// Find a specific subscription by name
auto puppySubscription = *syncedRealm.subscriptions().find("puppies");
CHECK(puppySubscription.name == "puppies");
// Get information about the subscription
CHECK(puppySubscription.object_class_name == "Dog");
CHECK(puppySubscription.query_string == "age < 3");

Para actualizar un conjunto de suscripciones, usa la función subscription().updates(). Esto te da acceso a un mutable_sync_subscription_set donde puedes usar la función add() para añadir una nueva suscripción de sincronizar.

Esta plantilla requiere el tipo de objeto Realm que deseas sincronizar, y un nombre de string para la suscripción.

You can subscribe to all objects of a type. This enables the synced realm to read and write any objects of the type where the user's permissions match the server-side permissions.

auto updateSubscriptionSuccess =
syncedRealm.subscriptions()
.update([](realm::mutable_sync_subscription_set &subs) {
subs.add<realm::Dog>("dogs");
})
.get();
// The .update() function returns a bool, which confirms whether or not the
// update succeeded
REQUIRE(updateSubscriptionSuccess == true);
// You can check the .size() of the subscription set, which tells you the
// number of sync_subscription objects in the set
CHECK(syncedRealm.subscriptions().size() == 1);

If you only want to subscribe to a subset of objects, provide a query to filter the subscription.

updateSubscriptionSuccess =
syncedRealm.subscriptions()
.update([](realm::mutable_sync_subscription_set &subs) {
subs.add<realm::Dog>(
"puppies", [](auto &obj) { return obj.age < 3; });
})
.get();
REQUIRE(updateSubscriptionSuccess == true);
CHECK(syncedRealm.subscriptions().size() == 1);

Cuando filtras una suscripción, no puedes guardar objetos que no correspondan con el filtro. En este ejemplo, la query coincide con Dog objetos cuyo age es menor que 3. El realm no sincroniza a ningún perro de 3 años o más. Este filtro también se aplica a los guardados. Si intentas escribir un objeto Dog donde el age es 4, obtendrás un error compensatorio de escritura y la escritura se revertirá.

Nota

The C++ SDK does not yet support the full range of query expressions that the other SDKs provide.

Para actualizar un conjunto de suscripciones, use la subscription().updates() función. Esto le da acceso a un conjunto mutable_sync_subscription_set donde puede usar la update_subscription() función para actualizar una suscripción de sincronización específica.

You can change a sync_subscription's query in an update. You can add, remove, or update the query string for a given sync_subscription.

updateSubscriptionSuccess =
syncedRealm.subscriptions()
.update([](realm::mutable_sync_subscription_set &subs) {
subs.update_subscription<realm::Dog>(
"puppies", [](auto &obj) { return obj.age < 2; });
})
.get();
REQUIRE(updateSubscriptionSuccess == true);

Para actualizar un conjunto de suscripciones, use la subscription().updates() función. Esto le da acceso a un conjunto de suscripciones mutable_sync_subscription_set donde puede usar las funciones remove() o clear() para eliminar suscripciones.

Puedes eliminar una suscripción específica por nombre usando la función remove(). Eliminar una suscripción por nombre genera un error si no existe, por lo que debes comprobar si existe antes de eliminarla.

auto removeSubscriptionSuccess =
syncedRealm.subscriptions()
.update([](realm::mutable_sync_subscription_set &subs) {
subs.remove("dogs");
})
.get();
REQUIRE(removeSubscriptionSuccess == true);

You can remove all subscriptions in a subscription set using the clear() function.

// You can use .clear() inside a mutable_sync_subscription_set to clear all
// sync_subscription objects from the set
auto updateSubscriptionSuccess =
syncedRealm.subscriptions()
.update(
[](realm::mutable_sync_subscription_set &subs) { subs.clear(); })
.get();
CHECK(updateSubscriptionSuccess == true);
CHECK(syncedRealm.subscriptions().size() == 0);

Después de actualizar las suscripciones, llame refresh() a en el dominio. Esto actualiza el dominio y los objetos pendientes administrados por este para que apunten a los datos más recientes.

syncedRealm.refresh();

Volver

Sync Data