-
Notifications
You must be signed in to change notification settings - Fork 5
Subscribing to Queries
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
.
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.
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
.
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.
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.
Home | Setup Guide | API Docs | Full Code API Docs
© Copyright 2014-2019 SciActive.com