Skip to content

Commit 625be75

Browse files
simon-idrichardlau
authored andcommitted
lib: add return value for DC channel.unsubscribe
PR-URL: #40433 Reviewed-By: Vladimir de Turckheim <vlad2t@hotmail.com> Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de> Reviewed-By: Michael Dawson <midawson@redhat.com> Reviewed-By: Bryan English <bryan@bryanenglish.com> Reviewed-By: Zijian Liu <lxxyxzj@gmail.com>
1 parent 5389b8a commit 625be75

File tree

3 files changed

+23
-8
lines changed

3 files changed

+23
-8
lines changed

doc/api/diagnostics_channel.md

+10
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,17 @@ channel.subscribe((message, name) => {
156156

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

159+
<!-- YAML
160+
added:
161+
- v14.17.0
162+
changes:
163+
- version: REPLACEME
164+
pr-url: https://github.com/nodejs/node/pull/40433
165+
description: Added return value.
166+
-->
167+
159168
* `onMessage` {Function} The previous subscribed handler to remove
169+
* Returns: {boolean} `true` if the handler was found, `false` otherwise.
160170

161171
Remove a message handler previously registered to this channel with
162172
[`channel.subscribe(onMessage)`][].

lib/diagnostics_channel.js

+9-7
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,17 @@ class ActiveChannel {
3232

3333
unsubscribe(subscription) {
3434
const index = ArrayPrototypeIndexOf(this._subscribers, subscription);
35-
if (index >= 0) {
36-
ArrayPrototypeSplice(this._subscribers, index, 1);
35+
if (index === -1) return false;
3736

38-
// When there are no more active subscribers, restore to fast prototype.
39-
if (!this._subscribers.length) {
40-
// eslint-disable-next-line no-use-before-define
41-
ObjectSetPrototypeOf(this, Channel.prototype);
42-
}
37+
ArrayPrototypeSplice(this._subscribers, index, 1);
38+
39+
// When there are no more active subscribers, restore to fast prototype.
40+
if (!this._subscribers.length) {
41+
// eslint-disable-next-line no-use-before-define
42+
ObjectSetPrototypeOf(this, Channel.prototype);
4343
}
44+
45+
return true;
4446
}
4547

4648
get hasSubscribers() {

test/parallel/test-diagnostics-channel-object-channel-pub-sub.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,12 @@ assert.ok(channel instanceof Channel);
3535
channel.publish(input);
3636

3737
// Should not publish after subscriber is unsubscribed
38-
channel.unsubscribe(subscriber);
38+
assert.ok(channel.unsubscribe(subscriber));
3939
assert.ok(!channel.hasSubscribers);
4040

41+
// unsubscribe() should return false when subscriber is not found
42+
assert.ok(!channel.unsubscribe(subscriber));
43+
4144
assert.throws(() => {
4245
channel.subscribe(null);
4346
}, { code: 'ERR_INVALID_ARG_TYPE' });

0 commit comments

Comments
 (0)