realm-js icon indicating copy to clipboard operation
realm-js copied to clipboard

Way to remove event listeners without keeping a reference of Realm.Results

Open rossicler-hostalky opened this issue 1 year ago • 3 comments

Problem

Can't easily get access to a "unsubscribe" function for event listeners added. Currently, you need to keep a reference of Realm.Results to be able to remove event listeners later on, but sometimes you don't really need to keep that in memory for any reason other than removing listeners at some point in the future.

This is linked to an issue I create some days ago, in which I found a workaround this is the link if anyone is interested.

Solution

My suggested solution is to return a "unsubscribe" function when adding an event listener. This is used in some web js listeners/subscriptions, which should be quite simple for developers to understand and use it.

Example:

const unsubListener;
export const getItems = async () => {
  const items = realm.objects(ItemSchema);
  
  if (unsubListener) unsubListener();
  unsubListener = items.addListener(itemListener);
  
  return ParseJSON(items);
}

Alternatives

As an alternative solution, you can add a name your event listeners, also allowing to remove listeners by name.

Example:

export const getItems = async () => {
  const items = realm.objects(ItemSchema);
  
  const listenerName = "myListener";
  // this can replace any existing listener with the same name
  // similar to how flexible realm subscriptions work
  items.addListener(itemListener, { name: listenerName });

  // also add the possibility to remove listener by name
  items.removeListenerByName("someOtherListener");
  
  return ParseJSON(items);
}

How important is this improvement for you?

I would like to have it but have a workaround

Feature would mainly be used with

Atlas Device Sync

rossicler-hostalky avatar Aug 09 '23 19:08 rossicler-hostalky

Thank you for your suggestion and two proposals. As a third proposal, I think we should consider to return a token like Realm Swift does: https://www.mongodb.com/docs/realm/sdk/swift/react-to-changes/#register-a-collection-change-listener

kneth avatar Aug 11 '23 14:08 kneth

That would also work, and it would be good to keep similar approaches from other realm sdks.

rossicler-hostalky avatar Aug 24 '23 16:08 rossicler-hostalky