Skip to main content

subscription

Calling any subscribe method, e.g. realm.object.subscribe() returns a Subscription object.

This subscription emits update events whenever a message is received and provides .update() and .cancel() methods to to control the subscription's lifecycle.

Events

update

emitted whenever the result set of a subscription changes. The callback receives two arguments:

  • fullState a map with object id to object data, reflecting the current state of all objects matching the subscription
  • changes an object with added, updated and removed properties, each containing a list with object id to object data
const subscription = realm.object.subscribe({where: ['type="deliveryRider"']});
subscription.on('update', (fullState, changes) => {
// list of delivery riders
})

Methods

update(options)

Update allows you to change the parameters for an existing subscription. This is quite powerful as it allows you to implement features such as subscriptions that move as your app's viewport changes, polygonal roaming geofences or real time filters for results.

// subscribe for your map's initial viewport
const mapSubscription = await realm.object.subscribe({
executeImmediatly: true,
shape: {
west: 13.377692047310838,
north: 52.51660212363485,
east: 13.463014670056378,
south: 52.512515547246664,
},
where: ['type="car"']
})

// update the subscription as the user pans the viewport
mapSubscription.update({
shape: {
west: 13.377692047310818,
north: 52.51660212363475,
east: 13.463014670056318,
south: 52.512515547246674,
}
})

cancel()

Notifies the server that you are no longer interested in updates for this subscription. Also clears all event listeners

on(eventName, callback, context)

Listen to update events. This is part of the regular EventEmitter interface

  • eventName the name of the event. update for subscriptions
  • callback a function that will be invoked when the event occurs
  • context an optional context argument. Gets you around using .bind(this)
// listen to update events, passing a function
subscription.on('update', data => {/*...*/})

// a context makes it easier to invoke methods of a class
class SubscriptionHandler{
constructor(subscription) {
this.subscription = subscription;
this.subscription.on('update', this.handleUpdate, this );
}

handleUpdate(data) {
// will be invoked with the correct value of this
}

destroy() {
this.subscription.cancel();
}
}

off(eventName, callback, context)

Removes an event handler that was previously registered with .on(...). Please note that this does not notify the server to stop sending updates - use .cancel() for that.

  • eventName the name of the event. update for subscriptions
  • callback a function that will be invoked when the event occurs
  • context an optional context argument. Gets you around using .bind(this)