Realm.open not delivering data


#1

Hi again. I figured out a lot already and offline sync is working like a charm now. But…
When I want to get data in online mode directly from the realm cloud (before syncing), I get no documents.
Here is my code:

let realm = Realm.open({
    path: 'places.realm',
    sync: {
      user: user,
       url: `realms://${REALM_SERVER}/user/places`,
       error: (session,err) => console.log("SE",err),
       validate_ssl: false,
       fullSynchronisation: false,
       partial: true
    },
    schema: [PlacesSchema]
  })
  .then(realm => {
    Reactotron.log('placeids',placeids)
    let obj = realm.objects("places").filtered(placeids);

  })
  .catch(e => Reactotron.error(e));

It works only if I add let subscription = obj.subscribe();. And it then works only at the second try since then the objects are subscribed, I guess.
My question is, is there something wrong with the code and how can I get data from a not yet synced realm. Is the subscription mandatory (by design)? If so, I guess I need to add a listener and wait for the subscription to finish before showing the results in the UI?


#2

You are using a partially synced realm so you have to subscribe to every result set, wait for it to finish subscribing, then then use it. If your result set is large, the subscription process can take a few seconds. e.g.

let obj = realm.objects("places").filtered(placeids);
let subscription = obj.subscribe();
subscription.addListener((state) => {
    if (state === Realm.Sync.SubscriptionState.Complete) {
        // use results
    }
})

There is a useful method in the tests you can use to subscribe via a promise.

  function subscribe(results) {
      const subscription = results.subscribe();
      return new Promise((resolve, reject) => {
          subscription.addListener((subscription, state) => {
              if (state === Realm.Sync.SubscriptionState.Complete) {
                  resolve();
              }
              else if (state === Realm.Sync.SubscriptionState.Error) {
                  reject();
              }
          });
          setTimeout(() => reject("listener never called"), 5000);
      });
  }

so you usage would be:

let obj = realm.objects("places").filtered(placeids);
subscribe(obj).then(() => {
// use results
})

Edit that to fit your needs.