When to open realms async vs sync

I read on Realm Sync documentation that realms should be opened asynchronously on the very first app open and otherwise opened synchronously. When I implemented this, no data populated to the cloud whenever realms were opened synchronously, although the changes happened on device just fine. What I’m thinking now is:

  1. open realm synchronously and store it in a variable, say db
  2. start loading data, etc from the realm
  3. start opening the realm asynchronously and when it opens, set db equal to this new realm instance

Am I thinking about sync vs async realms correctly? Is there a better pattern to handle this case?

The pattern suggested in the documentation does work so we need to understand the difference between that and what you’re doing.

It would be helpful to see what code you’re using to do the initial async open and then the code used to open it synchronously. Also include your platform.

I’m using React Native. Here’s the function that I call to open a connection to Realm.

shouldConnectAsync is passed in as true when the partition value is changed (on login) and the database variable is exported from this file and used throughout the app.

export const connect = async (shouldConnectAsync?: boolean) => {
  if (!app.currentUser) {
    return Promise.reject(new Error('Current user not found'))
  }

  const partitionValue = getPartition() // This gets the partition value for the current user

  if (!partitionValue) {
    return Promise.reject(new Error('Authorization failed'))
  }

  const config = {
    sync: {
      user: app.currentUser,
      partitionValue,
    },
    schema,
  }

  database = shouldConnectAsync ? await Realm.open(config) : new Realm(config)
}

Looks like this was actually related to this error: Keep getting BadChangeset Error (ProtocolErrorCode=212) in Realm Sync. Looks like a complete coincidence that it started happening right after we made this change to opening sync vs async. Seems to be resolved with realm 10.1.3.

This seems to work just fine on simulators once upgraded to 10.1.3, but for some reason whenever it’s loaded onto an iOS device (release mode), the same issue arises. The SDK version showing up when on the simulators is ios vRealmJS/10.1.3 (which I assume is correct) and the one coming in from the device is react-native vRealmJS/10.0.1 (this one has the bug). I’ve tried clearing node_modules, the ios build folder, pods, and it still isn’t using the same SDK version.

I have also noticed that you cannot use aysncOpen() when trying to open a Realm on a background thread. asyncOpen always forces the callback on the primary thread. Which means that if you want to open Realm to write to it on a background thread, you need to use Realm.open() instead.

I wrote a Medium article on this last moth.

Richard

2 Likes