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 a Sync Session - React Native SDK

When you use Atlas Device Sync, the React Native SDK syncs data with Atlas in the background using a sync session. A sync session starts whenever you open a synced realm.

Before you can manage a sync session, you must perform the following:

  1. Open a synced realm

  2. Agregar una suscripción de sincronización

  3. Envuelva los componentes que utilizan el useRealm() Gancho para un dominio sincronizado con los AppProvider UserProvider RealmProvider componentes, y. Para obtener más información sobre cómo configurar y abrir un dominio sincronizado, consulte "Abrir un dominio sincronizado".

Acceda a un dominio sincronizado en un componente con el gancho useRealm(). Acceda a la sesión de sincronización con el dominio. Propiedad Realm.syncSession.

import React, {useEffect} from 'react';
import {Context} from '../RealmConfig';
const {useRealm} = Context;
function AccessSyncSession() {
const realm = useRealm();
async function workWithSyncSession() {
const {syncSession} = realm;
// Do stuff with sync session...
}
// ...
}

Al abrir un reino sincronizado, se inicia una sesión de sincronización. Puedes pausar y reanudar la sesión de sincronización del reino. Si tienes más de un reino abierto, la pausa no afecta las sesiones de sincronización de los demás.

To pause synchronization, use the Realm.syncSession.pause() method. To resume synchronization, use the Realm.syncSession.resume() method.

import React, {useEffect, useState} from 'react';
import {Context} from '../RealmConfig';
const {useRealm} = Context;
function ToggleSyncSession() {
const realm = useRealm();
const [isPaused, setIsPaused] = useState(false);
async function toggleSyncSession() {
if (isPaused) {
await realm.syncSession?.resume();
} else {
await realm.syncSession?.pause();
}
setIsPaused(!isPaused);
}
return (
<Button
title={isPaused ? 'Pause Sync' : 'Unpause Sync'}
onPress={toggleSyncSession}
/>
);
}

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.

Para comprobar el progreso de subida y descarga de una sesión de sincronización, añade una notificación de progreso con Realm.syncSession.addProgressNotification() método.

El método Realm.syncSession.addProgressNotification() toma los siguientes tres parámetros:

  • Un parámetro direction. Ajuste en "upload" para registrar notificaciones de carga de datos. Establécelo en "download" para registrar notificaciones al descargar datos.

  • A mode parameter. Set to "reportIndefinitely" for the notifications to continue until the callback is unregistered using Realm.syncSession.removeProgressNotification(). Set to "forCurrentlyOutstandingWork" for the notifications to continue until only the currently transferable bytes are synced.

  • A callback function parameter that has the arguments transferred and transferable. transferred is the current number of bytes already transferred. transferable is the total number of bytes already transferred plus the number of bytes pending transfer.

Nota

Flexible Sync progress notifications are not yet fully supported. When using Flexible Sync, downloads only report notifications after changes are integrated. Partition-Based Sync provides ongoing notifications as changes progress downloading. Uploads report ongoing progress notifications for both Sync Modes.

The following example registers a callback on the syncSession to listen for upload events indefinitely. The example writes to the realm and then unregisters the syncSession notification callback.

import React, {useEffect, useState} from 'react';
import {SyncedRealmContext} from '../RealmConfig';
const {useRealm} = SyncedRealmContext;
import {Text} from 'react-native';
function CheckUploadProgress() {
const realm = useRealm();
const [uploadProgressPercent, setUploadProgressPercent] = useState(0);
useEffect(() => {
const progressNotificationCallback = (transferred, transferable) => {
// Convert decimal to percent with no decimals
// (e.g. 0.6666... -> 67)
const percentTransferred =
parseFloat((transferred / transferable).toFixed(2)) * 100;
setUploadProgressPercent(percentTransferred);
};
// Listen for changes to connection state
realm.syncSession?.addProgressNotification(
Realm.ProgressDirection.Upload,
Realm.ProgressMode.ReportIndefinitely,
progressNotificationCallback,
);
// Remove the connection listener when component unmounts
return () =>
realm.syncSession?.removeProgressNotification(
progressNotificationCallback,
);
// Run useEffect only when component mounts
}, []);
return <Text>Percent Uploaded: {uploadProgressPercent} %</Text>;
}
import React, {useEffect, useState} from 'react';
import {Context} from '../RealmConfig';
const {useRealm} = Context;
import {Text} from 'react-native';
function CheckUploadProgress() {
const realm = useRealm();
const [uploadProgressPercent, setUploadProgressPercent] = useState(0);
useEffect(() => {
const progressNotificationCallback: Realm.ProgressNotificationCallback = (
transferred,
transferable,
) => {
// Convert decimal to percent with no decimals
// (e.g. 0.6666... -> 67)
const percentTransferred =
parseFloat((transferred / transferable).toFixed(2)) * 100;
setUploadProgressPercent(percentTransferred);
};
// Listen for changes to connection state
realm.syncSession?.addProgressNotification(
Realm.ProgressDirection.Upload,
Realm.ProgressMode.ReportIndefinitely,
progressNotificationCallback,
);
// Remove the connection listener when component unmounts
return () =>
realm.syncSession?.removeProgressNotification(
progressNotificationCallback,
);
// Run useEffect only when component mounts
}, []);
return <Text>Percent Uploaded: {uploadProgressPercent} %</Text>;
}

El diseño offline-first de Realm significa que generalmente no necesitas verificar el estado actual de la conexión de red, ya que los datos se sincronizan en segundo plano cuando hay una conexión disponible. Dicho esto, el SDK de Realm proporciona métodos para obtener el estado actual de la conexión de red con el servidor.

To check the current state of the connection to the server, call Realm.syncSession.isConnected(). This method returns a boolean that is true if there is a network connection and the sync session is active.

To listen for connection state changes, call Realm.syncSession.addConnectionNotification(), passing a callback function to handle network changes as the argument. To unregister the listener, pass the same callback function to Realm.syncSession.removeConnectionNotification().

import React, {useState, useEffect} from 'react';
import {SyncedRealmContext} from '../RealmConfig';
const {useRealm} = SyncedRealmContext;
import {Text} from 'react-native';
function CheckNetworkConnection() {
const realm = useRealm();
const [isConnected, setIsConnected] = useState(
realm.syncSession?.isConnected(),
);
useEffect(() => {
const connectionNotificationCallback = (newState, oldState) => {
console.log('Current connection state: ' + newState);
console.log('Previous connection state: ' + oldState);
setIsConnected(realm.syncSession?.isConnected());
};
// Listen for changes to connection state
realm.syncSession?.addConnectionNotification(
connectionNotificationCallback,
);
// Remove the connection listener when component unmounts
return () =>
realm.syncSession?.removeConnectionNotification(
connectionNotificationCallback,
);
// Run useEffect only when component mounts
}, []);
return (
<Text>
{isConnected ? 'Connected to Network' : 'Disconnected from Network'}
</Text>
);
}
import React, {useState, useEffect} from 'react';
import {Context} from '../RealmConfig';
const {useRealm} = Context;
import {Text} from 'react-native';
function CheckNetworkConnection() {
const realm = useRealm();
const [isConnected, setIsConnected] = useState(
realm.syncSession?.isConnected(),
);
useEffect(() => {
const connectionNotificationCallback: Realm.ConnectionNotificationCallback =
(newState, oldState) => {
console.log('Current connection state: ' + newState);
console.log('Previous connection state: ' + oldState);
setIsConnected(realm.syncSession?.isConnected());
};
// Listen for changes to connection state
realm.syncSession?.addConnectionNotification(
connectionNotificationCallback,
);
// Remove the connection listener when component unmounts
return () =>
realm.syncSession?.removeConnectionNotification(
connectionNotificationCallback,
);
// Run useEffect only when component mounts
}, []);
return (
<Text>
{isConnected ? 'Connected to Network' : 'Disconnected from Network'}
</Text>
);
}

Habilitar multiplexación de sesiones Para consolidar varias sesiones de sincronización de una aplicación Realm. Utilice la multiplexación de sesiones solo si detecta errores al alcanzar el límite de descriptores de archivo y sabe que está utilizando muchas sesiones de sincronización.

To enable session multiplexing, call Realm.App.Sync.enableSessionMultiplexing() with your Realm.App.

import React, {useEffect} from 'react';
import {Context} from '../RealmConfig';
import {AppProvider, UserProvider, useUser, useApp, Realm} from '@realm/react';
function AppWrapper() {
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={<LogIn />}>
<RealmWrapper>
<RestOfApp />
</RealmWrapper>
</UserProvider>
</AppProvider>
);
}
type RealmWrapperProps = {
children: React.ReactNode;
};
function RealmWrapper({children}: RealmWrapperProps) {
const app = useApp();
Realm.App.Sync.enableSessionMultiplexing(app);
return <RealmProvider sync={{flexible: true}}>{children}</RealmProvider>;
}

Volver

Administrar suscripciones de sincronización flexible

En esta página