我正在开发一个offline-first在 React Native 上使用 Realm Sync 的应用程序。
我想要解决的具体编程问题是如何在我的应用程序中使用 React Native 实现这种离线优先的行为,以便登录的用户无论在线还是离线都可以获得无缝的体验。我正在寻找能够说明使用 Realm Sync 实现离线优先的最佳实践的代码。
在离线优先和 demo app in the MongoDB Realm documentation 方面,原本优秀的 Realm 文档非常有限。实现同步,但不具备离线功能。当然,我的出发点是该应用程序,因为它是文档和论坛中推荐的应用程序。
我已经测试了 iOS Swift 和 React Native“任务跟踪器”应用程序,它们不具备当前实现的离线优先功能,他们的工程师也确认了这一点。
该应用的 TaskProvider.js
中的重要代码是:
useEffect(() => {
const config = {
sync: {
user: user,
partitionValue: projectPartition,
},
};
// open a realm for this particular project
Realm.open(config).then((projectRealm) => {
realmRef.current = projectRealm;
const syncTasks = projectRealm.objects("Task");
let sortedTasks = syncTasks.sorted("name");
setTasks([...sortedTasks]);
sortedTasks.addListener(() => {
setTasks([...sortedTasks]);
});
});
// ...
}, [user, projectPartition]);
由于我需要在自己的应用程序中使用这样的代码,所以第一个问题是如何更改此代码以正确执行离线优先使用。此外,如果您已获得可在 React Native 上运行的离线优先 Realm Sync 应用程序,请提供链接或相关示例代码。
最佳答案
我提交了一个 PR,其中包含了示例 Task Tracker App by MongoDB Realm Sync更具离线能力。这不是一个完整的解决方案,但它解决了离线时任务列表无法访问的主要问题。
一个重要的一点是,要同步后台 Realm 的更改,需要同步打开,而不是异步打开。
TaskProvider.js
的新代码以及下面链接的文档中的注释:
useEffect(() => {
// You may want to sync changes in the background to display partial data to
// the user while the synced realm downloads data from the server,
// preventing the user experience from being blocked. We recommend syncing
// changes in the background for applications in which the user's device
// may go offline.
const OpenRealmBehaviorConfiguration = {
type: 'openImmediately',
};
// Create a Configuration object, which must include the sync property
// defining a SyncConfiguration object. Set this
// OpenRealmBehaviorConfiguration object as the value for the
// newRealmFileBehavior and existingRealmFileBehavior fields of
// the SyncConfiguration.
const config = {
sync: {
user: user,
partitionValue: projectPartition,
// The behavior to use when this is the first time opening a realm.
newRealmFileBehavior: OpenRealmBehaviorConfiguration,
// The behavior to use when a realm file already exists locally,
// i.e. you have previously opened the realm.
existingRealmFileBehavior: OpenRealmBehaviorConfiguration,
},
};
// open a realm for this particular project
Realm.open(config).then((projectRealm) => {
realmRef.current = projectRealm;
const syncTasks = projectRealm.objects('Task');
let sortedTasks = syncTasks.sorted('name');
setTasks([...sortedTasks]);
sortedTasks.addListener(() => {
setTasks([...sortedTasks]);
});
});
//...
}, [user, projectPartition]);
Sync Changes Between Devices - React Native SDK — MongoDB Realm
正如 PR 中所述,这仍然存在重大局限性。因此,我继续从那些使用 Realm Sync 和 React Native 来实现离线优先应用程序的人那里寻找更完整的实现细节或代码示例。
关于mongodb - React Native 上的 Realm Sync 离线优先 : how to implement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68453423/