Skip to content
This repository was archived by the owner on Mar 10, 2020. It is now read-only.

pubsub.unsubscribe without handler reference #437

Merged
merged 7 commits into from
Feb 26, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions SPEC/PUBSUB.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ 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.
The other options is to use this method with only `topic` as input, without the need to keep a reference to the `handler` function.
This works like `EventEmitter.remoteAllListeners`, removes all listeners from the given topic.

**Example:**

Expand Down Expand Up @@ -78,6 +80,25 @@ ipfs.pubsub.subscribe(topic, receiveMsg, (err) => {
})
```

Or removing all listeners:
```JavaScript
const topic = 'fruit-of-the-day'
const receiveMsg = (msg) => console.log(msg.toString())

ipfs.pubsub.subscribe(topic, receiveMsg, (err) => {
if (err) {
return console.error(`failed to subscribe to ${topic}`, err)
}

console.log(`subscribed to ${topic}`)

setTimeout(() => {
// Will unsubscribe ALL handlers for the given topic
ipfs.pubsub.unsubscribe(topic);
}, 1000)
})
```

A great source of [examples][] can be found in the tests for this API.

#### `pubsub.publish`
Expand Down
16 changes: 16 additions & 0 deletions src/pubsub/unsubscribe.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,21 @@ module.exports = (createCommon, options) => {
)
})
})
it('should subscribe and unsubscribe with no handler', (done) => {
const someTopic = getTopic()
const handler = (msg) => {}
ipfs.pubsub.subscribe(someTopic, handler, (err) => {
expect(err).to.not.exist()
ipfs.pubsub.unsubscribe(someTopic)
setTimeout(() => {
// Assert unsubscribe worked
ipfs.pubsub.ls((err, topics) => {
expect(err).to.not.exist()
expect(topics).to.eql([])
done()
})
}, 500)
})
})
})
}