diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index 16b47db3bf6cc4..90a3b1fb6ba41c 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -156,7 +156,17 @@ channel.subscribe((message, name) => { #### `channel.unsubscribe(onMessage)` + + * `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)`][]. diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index c29c9ff0052405..7860e8934494d2 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -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() { diff --git a/test/parallel/test-diagnostics-channel-object-channel-pub-sub.js b/test/parallel/test-diagnostics-channel-object-channel-pub-sub.js index cbc5b4d2e9a953..9498419b806ca8 100644 --- a/test/parallel/test-diagnostics-channel-object-channel-pub-sub.js +++ b/test/parallel/test-diagnostics-channel-object-channel-pub-sub.js @@ -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' });