Skip to content
This repository has been archived by the owner on Dec 11, 2022. It is now read-only.

Subscribing to Queries

Hunter Perrin edited this page Jun 12, 2019 · 12 revisions

Subscribing to a query lets you receive updates to that query. This is a powerful tool for collaborative apps. It's also just as easy as making a regular entity query.

Before we get started, you can follow the PubSub Server Setup page to set up your own Nymph PubSub server.

When you make an entity query, to subscribe to that query, call subscribe on the promise instead of then.

Subscribing to a Query
let smiths = [];
Nymph.getEntities(
  {
    class: User.class
  },
  {
    type: '&',
    like: ['name', '% Smith']
  }
).subscribe(update => {
  // This function will be called once initially with an array of
  // entities, then again every time there's a change with an
  // update object.
  // The updateArray function will add any newly matching entities,
  // update any existing entities that have changed, and remove any
  // entities that no longer match (including deleted entities).
  PubSub.updateArray(smiths, update)
}, errObj => {
  alert('Error: ' + errObj.textStatus);
});

You can also receive a count of how many subscribers there are to that query.

Getting Subscriber Count
let smiths = [];
Nymph.getEntities(
  {
    class: User.class
  },
  {
    type: '&',
    like: ['name', '% Smith']
  }
).subscribe(update => {
    PubSub.updateArray(smiths, update);
}, errObj => {
    alert('Error: '+errObj.textStatus);
}, count => {
    // This function will be called each time the count of subscribers to this query changes.
    console.log(`There are now ${count} users watching the Smiths.`);
});

To unsubscribe from the query, use the unsubscribe method on the subscription object returned by subscribe.

Unsubscribing From a Query
let smiths = [];
let subscription = Nymph.getEntities(
  {
    class: User.class
  },
  {
    type: '&',
    like: ['name', '% Smith']
  }
).subscribe(update => {
    PubSub.updateArray(smiths, update);
});

let unsubscribe = () => {
    subscription.unsubscribe();
};

You can subscribe to changes to an entity with the $subscribe method on the Entity object.

Subscribing to an Entity
let subscription = smithEntity.$subscribe(() => {
    if (smithEntity.guid == null) {
        if (confirm('Someone deleted Mr. Smith! Do you want to restore him?')) {
            smithEntity.$save();
        }
    } else {
        alert("Mr. Smith's entity has changed!");
    }
}, errObj => {
    alert('Error: ' + errObj.textStatus);
}, count => {
    console.log(`There are now ${count} users watching Mr. Smith.`);
});

let unsubscribe = () => {
    subscription.unsubscribe();
};

⚠️ Warning: Subscriptions can lead to resource leaks if left open. Take care to unsubscribe to every query you are no longer watching.

Clone this wiki locally