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

Gestionar una sesión de sincronización - C++ SDK

Cuando utilizas Atlas Device Sync, el SDK de Realm C++ sincroniza datos con Atlas en segundo plano usando una sesión de sincronización. La sesión de sincronización comienza cuando abres un Realm sincronizado.

The sync session manages the following:

  • Uploading and downloading changes to the realm

  • Supervisión del estado de sincronización

Before you can manage a sync session state, you must:

  1. Configure Flexible Sync on the Atlas App Services backend

  2. Open a Synced Realm

Puedes usar la función miembro get_sync_session() para obtener un objeto sync_session para cualquier dominio sincronizado. El SDK devuelve este objeto como opcional. Es un identificador ligero que puedes pasar por valor.

auto syncSession = realm.get_sync_session();

Tip

El diseño sin conexión del SDK significa que, por lo general, no es necesario verificar el estado actual de la conexión de red. Dicho esto, connection_state() La propiedad está disponible si su aplicación requiere alguna indicación del estado de la conexión.

Para comprobar el estado de la conexión, puedes leer la propiedad connection_state() de la instancia de sesión de sincronización directamente.

syncSession->connection_state();

También se puede observar el estado de la conexión con la función observe_connection_change(). Esta función registra una función de retorno que el SDK invoca cuando la sesión de sincronización subyacente cambia su estado de conexión.

auto connectionToken = syncSession->observe_connection_change(
[&](enum realm::sync_session::connection_state,
enum realm::sync_session::connection_state new_state) {
// Register a block to execute when connection state changes.
});

Si registra un detector de cambios de conexión, puede anular su registro al finalizar la escucha de cambios. Llame al método unregister_connection_change_observer() de la instancia de sesión de sincronización para anular el registro de un token de observación.

syncSession->unregister_connection_change_observer(connectionToken);

El estado de la conexión de red es distinto del estado de la conexión de Device Sync, que puedes comprobar con el método state(). Para obtener más información sobre el estado de conexión de la sincronización, consulta la documentación Comprobar el estado de sincronización en esta página.

You can pause and resume the sync session on the realm. Pausing a sync session only suspends that realm's sync session. If you have more than one open realm, suspend does not affect the sync sessions for other realms.

Para pausar una sesión de sincronización, llama al método pause() de la sesión de sincronización.

syncSession->pause();

Para reanudar una sesión de sincronización, llama al método resume() de la sesión de sincronización.

syncSession->resume();

For most applications, there is no need to manually pause and resume a sync session. However, there are a few circumstances under which you may want to pause or suspend a sync session:

  • You only want to sync after the user takes a specific action

  • You only want to sync during a certain time of the day

  • No debes intentar sincronizar cuando hay una mala conectividad de red

  • You want to explicitly force a sync session to connect

In the case of poor network connectivity, continually trying to establish a network connection can drain the user's device battery.

The case of explicitly forcing a sync session to connect is most commonly related to being offline for some time. The sync client attempts to connect, and upon failure, goes into exponential backoff. After being offline for a long time, the client may not immediately reconnect. Pausing and resuming the sync session explicitly forces the connection.

When you do pause a sync session, keep these things in mind:

  • If the client may be offline longer than the client maximum offline time, the client will be unable to resume syncing and must perform a client reset.

  • Pausing a sync session pauses it in both directions. Changes that your app makes on the device do not sync with the backend, and changes to the data in the backend or on other devices do not sync to the device. There is no way to pause only uploads or pause only downloads.

  • No pause una sesión de sincronización si desea que un cliente deje de sincronizarse permanentemente con el backend. Para ello, copie el contenido del dominio sincronizado en uno no sincronizado y utilice este último en el cliente.

No pauses la sincronización para detener la sincronización por períodos de tiempo indefinidos o rangos de meses y años. La funcionalidad no está diseñada ni probada para estos casos de uso. Podrías encontrar un rango de problemas al usarlo de esta manera.

You can use the sync_session's wait_for_upload_completion() and wait_for_download_completion() methods to wait for changes to upload to or download from Atlas. Both of these methods can optionally take a callback to execute when upload or download is complete.

To wait for all changes to upload to Atlas from your synced realm, use the member function wait_for_upload_completion().

syncSession->wait_for_upload_completion().get();

To wait for all changes from Atlas to download to your synced realm, use the member function wait_for_download_completion(). Refresh the realm after downloading any changes to be sure it reflects the most recent data.

syncSession->wait_for_download_completion().get();
realm.refresh();

You can use the sync_session's public member function state() to check whether the sync session is active. This returns an enum whose value reflects possible Device Sync states.

syncSession->state();

The sync connection state is distinct from the network connection state that you can check with the connection_state() method. For more information about network connection state, refer to the Check the Network Connection documentation on this page.

Realm automatically detects when a device regains connectivity after being offline and attempts to reconnect using an incremental backoff strategy.

You can choose to manually trigger a reconnect attempt with a sync session's reconnect() method instead of waiting for the duration of the incremental backoff. This is useful if you have a more accurate understanding of the network conditions and don't want to rely on Realm's automatic reconnect detection.

syncSession->reconnect();

When you call this method, the SDK forces all sync sessions to attempt to reconnect immediately. This resets any timers used for incremental backoff.

Calling this method does not guarantee the device can reconnect. If the SDK gets a fatal error, or if the device is already connected or is trying to connect, calling this method has no effect.

Importante

Cannot Reconnect Within Socket Read Timeout Duration

Realm tiene un tiempo de espera de lectura de socket por defecto de 2 minutos, donde Realm fallará si una operación de lectura no recibe datos durante una ventana de 2 minutos. Si llama a reconnect() dentro de esa ventana, el SDK no intentará reconectarse.

Volver

Write to a Synced Realm

En esta página