您可以使用单个 Realm 通过 Atlas Device Sync 来同步来自多个进程的数据。
您可能希望在多个进程中打开同步 Realm 的场景示例包括:
多窗口桌面应用程序,其中每个窗口都写入相同的同步 Realm。
从多个进程写入同步 Realm 的服务器应用程序。
在多个进程中打开同步 Realm
要从多个进程打开单个同步域,请执行以下操作:
创建一个使用标准 Flexible Sync 配置打开 Realm 的单个主进程。 主进程处理同步。
创建一个或多个从节点进程,使用断开连接的同步配置打开同一域。使用断开连接的同步配置,从节点进程可以读取 Realm 数据并将其写入 Realm,而无需处理同步。 主进程负责从节点进程的所有数据的同步。
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);
跨进程刷新数据
在多个进程之间共享同一个 Realm 文件时,Realm 内置了自动刷新功能。从一个进程写入的数据对其他进程可见。 通常,无需编写额外的逻辑来跨进程刷新数据。
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().
要同步强制更新通知其他进程所做的更改,请调用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');
或者,您可以使用Realm.refreshAsync()
异步强制更新其他进程所做更改的通知。
// Asynchronously refresh the realm in the background. await realm.refreshAsync(); final john = realm.find<Person>('John');