Sync Data from Multiple Processes
You can use a single realm to synchronize data from multiple processes using Atlas Device Sync.
Examples of scenarios where you might want to open a synced realm in multiple processes include:
A multi-window desktop application where each window writes to the same synced realm.
A server application that writes to a synced realm from multiple processes.
Open a Synced Realm in Multiple Processes
To open a single synced realm from multiple processes, perform the following:
Create a single main process that opens a Realm using a standard flexible sync configuration. The main process handles synchronization.
Create one or more secondary processes that open the same realm using a disconnected sync configuration. Using a disconnected sync configuration, the secondary processes reads and writes data to the realm without handling the synchronization. The main process handles the synchronization of all data for the secondary process.
To open a synced realm in the main process, use the Configuration.flexibleSync() constructor. For more information, refer to Open a Synced Realm.
// Same realm file location as secondary process final realmPath = path.join(Configuration.defaultStoragePath, 'synced.realm'); final flexibleConfig = Configuration.flexibleSync(currentUser, schema, path: realmPath); final realmWithSync = Realm(flexibleConfig);
To open a synced realm in a secondary process, create a Configuration
with the
Configuration.disconnectedSync()
constructor. Include the schema and any additional optional named arguments.
// Same realm file location as primary process final sameRealmPath = path.join(Configuration.defaultStoragePath, 'synced.realm'); final disconnectedSyncConfig = Configuration.disconnectedSync(schema, path: sameRealmPath); final realmWithDisconnectedSync = Realm(disconnectedSyncConfig);
Refresh Data across Processes
When sharing the same realm file between multiple processes, Realm has auto-refresh built-in. Data written from one process is visible to the other processes. Generally, you do not need to write additional logic to refresh data across processes.
However, occasionally the refresh may not happen immediately. In this case, you can trigger a manual refresh in a process with Realm.refresh() or Realm.refreshAsync().
To synchronously force update notifications for changes made by another process,
call Realm.refresh()
.
// Add object in one process realm.write(() { realm.add(Person('John')); });
// Call realm.refresh() in the secondary process // to trigger the data written in the main process // to register in the secondary process. realm.refresh(); final john = realm.find<Person>('John');
Alternatively, you can use Realm.refreshAsync()
to asynchronously force
update notifications for changes made by another process.
// Asynchronously refresh the realm in the background. await realm.refreshAsync(); final john = realm.find<Person>('John');