Skip to content

Commit

Permalink
lib: add return value for DC channel.unsubscribe
Browse files Browse the repository at this point in the history
PR-URL: #40433
Reviewed-By: Vladimir de Turckheim <[email protected]>
Reviewed-By: Stephen Belanger <[email protected]>
Reviewed-By: Gerhard Stöbich <[email protected]>
Reviewed-By: Michael Dawson <[email protected]>
Reviewed-By: Bryan English <[email protected]>
Reviewed-By: Zijian Liu <[email protected]>
  • Loading branch information
simon-id authored and richardlau committed Jan 25, 2022
1 parent 5389b8a commit 625be75
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 8 deletions.
10 changes: 10 additions & 0 deletions doc/api/diagnostics_channel.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,17 @@ channel.subscribe((message, name) => {

#### `channel.unsubscribe(onMessage)`

<!-- YAML
added:
- v14.17.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/40433
description: Added return value.
-->

* `onMessage` {Function} The previous subscribed handler to remove
* Returns: {boolean} `true` if the handler was found, `false` otherwise.

Remove a message handler previously registered to this channel with
[`channel.subscribe(onMessage)`][].
Expand Down
16 changes: 9 additions & 7 deletions lib/diagnostics_channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,17 @@ class ActiveChannel {

unsubscribe(subscription) {
const index = ArrayPrototypeIndexOf(this._subscribers, subscription);
if (index >= 0) {
ArrayPrototypeSplice(this._subscribers, index, 1);
if (index === -1) return false;

// When there are no more active subscribers, restore to fast prototype.
if (!this._subscribers.length) {
// eslint-disable-next-line no-use-before-define
ObjectSetPrototypeOf(this, Channel.prototype);
}
ArrayPrototypeSplice(this._subscribers, index, 1);

// When there are no more active subscribers, restore to fast prototype.
if (!this._subscribers.length) {
// eslint-disable-next-line no-use-before-define
ObjectSetPrototypeOf(this, Channel.prototype);
}

return true;
}

get hasSubscribers() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,12 @@ assert.ok(channel instanceof Channel);
channel.publish(input);

// Should not publish after subscriber is unsubscribed
channel.unsubscribe(subscriber);
assert.ok(channel.unsubscribe(subscriber));
assert.ok(!channel.hasSubscribers);

// unsubscribe() should return false when subscriber is not found
assert.ok(!channel.unsubscribe(subscriber));

assert.throws(() => {
channel.subscribe(null);
}, { code: 'ERR_INVALID_ARG_TYPE' });

0 comments on commit 625be75

Please sign in to comment.