From 1295a34481c0b87ed0c95224888d5be783ae4326 Mon Sep 17 00:00:00 2001 From: "fryorcraken.eth" Date: Mon, 19 Sep 2022 12:21:29 +1000 Subject: [PATCH] feat: return function to delete observer --- CHANGELOG.md | 4 ++++ src/lib/waku_relay/index.node.spec.ts | 6 ++++-- src/lib/waku_relay/index.ts | 18 ++++++++++++++++-- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9473bfa91c..b1bbc83148 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `WakuRelay.addObserver` now returns a function to delete the observer. + ### Changed - `queryCallbackOnPromise`'s return value has been simplified to `Promise`. diff --git a/src/lib/waku_relay/index.node.spec.ts b/src/lib/waku_relay/index.node.spec.ts index 3fb93e615c..05e6a62146 100644 --- a/src/lib/waku_relay/index.node.spec.ts +++ b/src/lib/waku_relay/index.node.spec.ts @@ -248,8 +248,10 @@ describe("Waku Relay [node only]", () => { // The promise **fails** if we receive a message on this observer. const receivedMsgPromise: Promise = new Promise( (resolve, reject) => { - waku2.relay.addObserver(reject, ["added-then-deleted-observer"]); - waku2.relay.deleteObserver(reject, ["added-then-deleted-observer"]); + const deleteObserver = waku2.relay.addObserver(reject, [ + "added-then-deleted-observer", + ]); + deleteObserver(); setTimeout(resolve, 500); } ); diff --git a/src/lib/waku_relay/index.ts b/src/lib/waku_relay/index.ts index b53cf9519e..0480bc23a4 100644 --- a/src/lib/waku_relay/index.ts +++ b/src/lib/waku_relay/index.ts @@ -131,12 +131,12 @@ export class WakuRelay extends GossipSub { * @param callback called when a new message is received via waku relay * @param contentTopics Content Topics for which the callback with be called, * all of them if undefined, [] or ["",..] is passed. - * @returns {void} + * @returns Function to delete the observer */ addObserver( callback: (message: WakuMessage) => void, contentTopics: string[] = [] - ): void { + ): () => void { if (contentTopics.length === 0) { if (!this.observers[""]) { this.observers[""] = new Set(); @@ -150,6 +150,20 @@ export class WakuRelay extends GossipSub { this.observers[contentTopic].add(callback); }); } + + return () => { + if (contentTopics.length === 0) { + if (this.observers[""]) { + this.observers[""].delete(callback); + } + } else { + contentTopics.forEach((contentTopic) => { + if (this.observers[contentTopic]) { + this.observers[contentTopic].delete(callback); + } + }); + } + }; } /**