Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add success return value in diagnostics_channel unsubscribe #40433

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions doc/api/diagnostics_channel.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,9 +264,14 @@ channel.subscribe((message, name) => {
added:
- v15.1.0
- v14.17.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/40433
description: Added return value. Added to channels without subscribers.
-->

* `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
20 changes: 13 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 Expand Up @@ -79,6 +81,10 @@ class Channel {
this.subscribe(subscription);
}

unsubscribe() {
return false;
}

get hasSubscribers() {
return false;
}
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' });