mirror of https://github.com/waku-org/js-waku.git
feat: return function to delete observer
This commit is contained in:
parent
32a55f707a
commit
1295a34481
|
@ -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<void>`.
|
||||
|
|
|
@ -248,8 +248,10 @@ describe("Waku Relay [node only]", () => {
|
|||
// The promise **fails** if we receive a message on this observer.
|
||||
const receivedMsgPromise: Promise<WakuMessage> = 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);
|
||||
}
|
||||
);
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
Loading…
Reference in New Issue