diff --git a/SPEC/PUBSUB.md b/SPEC/PUBSUB.md index ef5c14ca7..b8977ff72 100644 --- a/SPEC/PUBSUB.md +++ b/SPEC/PUBSUB.md @@ -50,7 +50,15 @@ A great source of [examples][] can be found in the tests for this API. If no `callback` is passed, a [promise][] is returned. -This works like `EventEmitter.removeListener`, as that only the `handler` passed to a `subscribe` call before is removed from listening. The underlying subscription will only be canceled once all listeners for a topic have been removed. +If the `topic` and `handler` are provided, the `handler` will no longer receive updates for the `topic`. This behaves like [EventEmitter.removeListener](https://nodejs.org/dist/latest/docs/api/events.html#events_emitter_removelistener_eventname_listener). If the `handler` is not equivalent to the `handler` provided on `subscribe`, no action will be taken. + +If **only** the `topic` param is provided, unsubscribe will remove **all** handlers for the `topic`. This behaves like [EventEmitter.removeAllListeners](https://nodejs.org/dist/latest/docs/api/events.html#events_emitter_removealllisteners_eventname). Use this if you would like to no longer receive any updates for the `topic`. + +**WARNING:** Unsubscribe is an async operation, but removing **all** handlers for a topic can only be done using the Promises API (due to the difficulty in distinguishing between a "handler" and a "callback" - they are both functions). If you _need_ to know when unsubscribe has completed you must use `await` or `.then` on the return value from + +```JavaScript +ipfs.pubsub.unsubscribe('topic') +``` **Example:** @@ -78,6 +86,17 @@ ipfs.pubsub.subscribe(topic, receiveMsg, (err) => { }) ``` +Or removing all listeners: +```JavaScript +const topic = 'fruit-of-the-day' +const receiveMsg = (msg) => console.log(msg.toString()) + +await ipfs.pubsub.subscribe(topic, receiveMsg); + +// Will unsubscribe ALL handlers for the given topic +await ipfs.pubsub.unsubscribe(topic); +``` + A great source of [examples][] can be found in the tests for this API. #### `pubsub.publish` diff --git a/src/pubsub/unsubscribe.js b/src/pubsub/unsubscribe.js index 98e6ee114..a5325cefd 100644 --- a/src/pubsub/unsubscribe.js +++ b/src/pubsub/unsubscribe.js @@ -57,5 +57,16 @@ module.exports = (createCommon, options) => { ) }) }) + + it('should subscribe 10 handlers and unsunscribe once with no reference to the handlers', async () => { + const count = 10 + const someTopic = getTopic() + for (let i = 0; i < count; i++) { + await ipfs.pubsub.subscribe(someTopic, (msg) => {}) + } + await ipfs.pubsub.unsubscribe(someTopic) + const topics = await ipfs.pubsub.ls() + expect(topics).to.eql([]) + }) }) }