同步Realm应该如何工作

时间:2018-01-23 15:05:23

标签: react-native realm

我是反应本地和领域的新手,但不是编程,所以我确定我做错了。

场景是我有一个使用领域的离线优先反应本机应用程序。

当我运行一个完全本地的域文件时,一切正常。我可以加载数据(来自手机通讯录)并与之互动。

realm: new Realm({schema: schemas, schemaVersion: 3,})

然后我尝试将它与Realm Object Server同步,如下所示:

        Realm.Sync.User.login(app_config.auth_uri, app_config.default_login, app_config.default_password).then(user => {
        console.log("logged into Realm Object Server")
        const config = {
            sync: {
                user: user,
                url: app_config.db_uri,
                error: err => console.log(err)
            },
            schema: schemas,
            schemaVersion: 3,
        };

        this.realm = new Realm(config);

    }).catch(error => {
        console.log('Error with sync setup to ' + app_config.auth_uri + ' with : ' + error)
    });

它连接但没有同步。 更糟糕的是,因为它现在处于异步上下文中,所有预期“领域”设置的都是失败的 - 许多“空”异常。

所以我的问题:

这应该如何运作。我的期望是我立即从两个电话获得一个领域,并且同步部分应该在后台发生。 如果它失败,即无法连接或失去连接,应用程序仍应正常工作。

我错了,有没有人有更全面的工作示例?

将继续搜索,但我非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果您创建了一个本地领域,然后想要成为一个同步的领域,则需要复制它:

https://realm.io/docs/cookbook/js/local-realm-to-synced/

或者,如果您使用上述new Realm创建具有同步配置的同步领域,或者在服务器上提前创建它,它将按照您的期望进行同步。

没有看到您正在使用的网址,很难完全确认您的问题。

注意:我添加了fullSyncronization标志,因为默认设置是部分同步的。

function getOpenRealm (app_config) {
  return new Promise((resolve, reject) => {
    Realm.Sync.User.login(app_config.auth_uri, app_config.default_login, app_config.default_password).then(user => {
      const config = {
        sync: {
          user: user,
          url: app_config.db_uri,
          error: err => console.log(err),
        },
        schema: schemas,
        schemaVersion: 3,
        fullSynchronization: true,
      }
      Realm.open(config).progress((transferred, transferable) => {
        const progressPercentage = transferred / (transferable / 100)
        console.log(`progress ${transferred}/${transferable} (${Math.round(progressPercentage, 2)}%)`)
      }).then(realm => {
        resolve(realm)
      }).catch((e) => { reject(e)})
    }).catch((e) => { reject(e)})
  })
}

getOpenRealm(app_config)
  .then(realm => {
    this.realm = realm
  })
  .catch(e => {})

或者使用async / await进行清洁...

async function getOpenRealm (app_config) {

  let user = await Realm.Sync.User.login(app_config.auth_uri, app_config.default_login, app_config.default_password)
  const config = {
    sync: {
      user: user,
      url: app_config.db_uri,
      error: err => console.log(err),
    },
    schema: schemas,
    schemaVersion: 3,
    fullSynchronization: true,
  }
  let realm = await Realm.open(config).progress((transferred, transferable) => {
    const progressPercentage = transferred / (transferable / 100)
    console.log(`progress ${transferred}/${transferable} (${Math.round(progressPercentage, 2)}%)`)
  })

  return realm
}

try {
  this.realm = await getOpenRealm(app_config)
}
catch(e) {
  // do what you will with e
}