Manage a Sync Session - Flutter SDK
On this page
When you use Atlas Device Sync, the Realm Flutter SDK syncs data with Atlas in the background using a sync session. The sync session starts whenever you open a synced realm.
The sync session manages the following:
Uploading and downloading changes to the realm
Pausing and resuming sync
Monitoring sync progress
Monitoring network connectivity
You can access the Session of any synced realm through the Realm.syncSession property.
Prerequisites
Before you can manage your sync session state, you must perform the following:
Wait for Changes to Upload and Download
To asynchronously wait for all changes to upload to Atlas from your synced realm, call Session.waitForUpload(). To asynchronously wait for all changes on Atlas to download to your synced realm, call Session.waitForDownload().
// Wait to download all pending changes from Atlas await realm.syncSession.waitForDownload(); // Add data locally realm.write(() { realm.addAll<Car>([ Car(ObjectId(), "Hyundai"), Car(ObjectId(), "Kia"), Car(ObjectId(), "Lincoln") ]); }); // Wait for changes to upload to Atlas before continuing execution. await realm.syncSession.waitForUpload();
Pause and Resume a Sync Session
To pause syncing for a session, call Session.pause(). The realm will not sync changes with Atlas while the session is paused.
To resume syncing a changes, call Session.resume().
You must manually call Session.pause()
and Session.resume()
for each
realm whose Sync session you want to pause and restart.
The sync state of one session has no impact on other open sessions.
The following code block demonstrates calling these methods:
// Pause the sync session realm.syncSession.pause(); // Data that you add while the sync session is paused does not sync to Atlas. // However, the data is still added to the realm locally. realm.write(() { realm.addAll<Car>([ Car(ObjectId(), "Volvo"), Car(ObjectId(), "Genesis"), Car(ObjectId(), "VW") ]); }); // Resume sync session. Now, the data you wrote to the realm // syncs to Atlas. realm.syncSession.resume();
When to Pause a Sync Session
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
You don't want to attempt to sync when there is poor network connectivity
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.
Do not pause a sync session if you want a client to permanently stop syncing with the backend. To permanently stop syncing, copy the contents of the synced realm into a non-synced realm, and use the non-synced realm in the client.
Do not pause sync to stop syncing for indefinite time periods or time ranges in months and years. The functionality is not designed or tested for these use cases. You could encounter a range of issues when using it this way.
Monitor Sync Upload Progress
To monitor Sync upload progress progress, call SyncSession.getProgressStream(). This method returns a Stream of
SyncProgress objects.
SyncProgress
provides the total number of transferrable bytes and the remaining
bytes to be transferred.
SyncSession.getProgressStream()
takes two arguments:
A ProgressDirection enum that must be set to
upload
. This specifies that the progress stream tracks uploads.A ProgressMode enum that can be set to
reportIndefinitely
orforCurrentlyOutstandingWork
.reportIndefinitely
sets notifications to continue until the callback is unregistered.forCurrentlyOutstandingWork
sets notifications to continue until only the currently-transferable bytes are synced.
final stream = realm.syncSession.getProgressStream( ProgressDirection.upload, ProgressMode.forCurrentlyOutstandingWork); late StreamSubscription streamListener; streamListener = stream.listen((syncProgressEvent) { if (syncProgressEvent.transferableBytes == syncProgressEvent.transferredBytes) { // Upload complete print('Upload complete'); // Stop listening to the Stream streamListener.cancel(); } });
Warning
Do Not Track Downloads
The ProgressDirection
enum also has a download
option to track down downloads.
The download
case provides planned future support for download progress notifications.
However, these notifications do not currently provide an accurate indicator of download progress.
Do not rely on ProgressDirection.download
for download progress notifications.
Monitor Network Connection
You can get the state of the current network connection with
Session.connectionState.
This returns a ConnectionState enum
that contains the network connection's state: connected
, disconnected
, or connecting
.
if (realm.syncSession.connectionState == ConnectionState.connected) { // ... do stuff }
Monitor the state of the network connection with
Session.connectionStateChanges.
This property returns a Stream of ConnectionStateChange
objects that updates when the network connection changes.
You can access the current and previous ConnectionState
from ConnectionStateChange
.
final connectionStream = realm.syncSession.connectionStateChanges; late StreamSubscription streamListener; streamListener = connectionStream.listen((connectionStateChange) { if (connectionStateChange.current == ConnectionState.connected) { print("Connected to Atlas Device Sync server"); streamListener.cancel(); } });