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 Device Data

Manage a Sync Session - Kotlin SDK

Esta página describe las sesiones de sincronización y cómo administrarlas en una aplicación mediante Sincronización flexible. Para obtener información detallada sobre Sincronización flexible, consulte Sincronización de dispositivos Atlas en la documentación de servicios de aplicaciones.

When you use Flexible Sync, the Realm Kotlin SDK syncs data with Atlas in the background using a sync session. The sync session starts whenever you open a synced realm.

val app = App.create(YOUR_APP_ID)
val user = app.login(credentials)
val config = SyncConfiguration.Builder(user, setOf(Task::class))
.build()
// Open the synced realm
val realm = Realm.open(config)
// Sync session is now active
// ... do something with the synced realm

The sync session manages the following:

  • Uploading and downloading changes to the realm

  • Pausar y reanudar la sincronización

  • Monitoring network connectivity

Puede acceder a la SyncSession de un único reino sincronizado a través de la propiedad realm.syncSession.

The Kotlin SDK manages communication with App Services at two levels:

  • connection state: the state of the network connection between a client device and your backend App.

  • estado de la sesión: estado de sincronización de un solo usuario, que se puede pausar y reanudar en el SDK a voluntad (consulte la sección Pausar y reanudar una sesión de sincronización).

Ambos estados determinan si los cambios locales de un usuario se sincronizan con el backend. La sincronización solo ocurre cuando SyncSession.ConnectionState es CONNECTED y SyncSession.State es ACTIVE DYINGo.

To asynchronously wait for all changes to upload to Atlas from your synced realm, call uploadAllLocalChanges. This method returns true when all changes have been uploaded.

To asynchronously wait for all changes on Atlas to download from the Device Sync server to your synced realm, call downloadAllServerChanges. This method returns true when all changes have been downloaded.

You can also include an optional timeout parameter to either method to determine the maximum amount of time before returning false. Note that the upload or download continues in the background even after returning false.

The following example demonstrates calling both methods with a timeout defined:

// Wait to download all pending changes from Atlas
realm.syncSession.downloadAllServerChanges(1.minutes)
// Add data locally
realm.write {
this.copyToRealm(Task().apply {
taskName = "Review proposal"
assignee = "Emma"
progressMinutes = 0
})
}
// Wait for local changes to be uploaded to Atlas
realm.syncSession.uploadAllLocalChanges(1.minutes)

Para pausar la sincronización de una sesión, llama a syncSession.pause(). El realm no sincronizará cambios con Atlas mientras la sesión esté en pausa.

Para reanudar la sincronización de cambios, llame a syncSession.resume().

Debes llamar manualmente a syncSession.pause() y syncSession.resume() para cada realm cuya sesión de sincronización desees pausar y reiniciar. El estado de sincronización de una sesión no tiene impacto sobre otras sesiones abiertas.

El siguiente bloque de código demuestra cómo llamar a estos métodos:

// Pause the sync session
// Data that you write while session is paused does not sync to Atlas
realm.syncSession.pause()
// Add data locally
realm.write {
this.copyToRealm(Task().apply {
taskName = "Submit expense report"
assignee = "Kevin"
progressMinutes = 0
})
}
// Resume sync session
// Local changes now sync to Atlas
realm.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.

Puede obtener el estado de la conexión de red actual comprobando el SyncSession.connectionState propiedad. Esto devuelve un valor enum de ConnectionState que indica el estado de la conexión de red. Los posibles estados son: CONNECTED, DISCONNECTED o CONNECTING.

if (realm.syncSession.connectionState == ConnectionState.CONNECTED) {
Log.i("Connected to network")
// ... do something
}

Monitor the state of the network connection with connectionStateAsFlow. This property returns a Flow of ConnectionStateChange objects that updates when the network connection changes. You can access the new and old ConnectionState from ConnectionStateChange.

val connectionFlow = realm.syncSession.connectionStateAsFlow()
connectionFlow.collect { ConnectionStateChange ->
if (ConnectionStateChange.newState == ConnectionState.CONNECTED) {
Log.i("Connected to Atlas Device Sync server")
}
}

Novedades en la versión 1.11.0.

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

En la versión y posteriores del SDK de Kotlin,1.11.0 puede optar por activar manualmente un intento de reconexión con App.Sync.reconnect() en lugar de esperar a que finalice la interrupción incremental. Esto es útil si comprende con mayor precisión las condiciones de la red (por ejemplo, al supervisar los cambios de red con en Android) y no desea depender de la ConnectivityManager detección automática de reconexión de Realm. El SDK también llama automáticamente a este método cuando un dispositivo desactiva el modo avión.

To manually trigger a reconnect attempt, call the App.Sync.reconnect() method, which is accessed through the App.Sync interface. Unlike SyncSession, which lets you access a single realm sync session, the App.Sync interface controls all sync sessions for your App.

app.sync.reconnect()

Al llamar a este método, el SDK obliga a que todas las sesiones de sincronización intenten reconectarse inmediatamente y restablece cualquier temporizador utilizado para el retroceso incremental.

Importante

Cannot Reconnect Within Socket Read Timeout Duration

Realm has an internal default socket read timeout of 2 minutes, where Realm will time out if a read operation does not receive any data within a 2-minute window. If you call App.Sync.reconnect() within that window, the Kotlin SDK does not attempt to reconnect.

Volver

Write to a Synced Realm

En esta página