Why does the VSCode Extension tutorial recommend subscribing a registered command to the context.subscriptions
?
It doesn't seem to be necessary or useful from what I can tell so far.
Here's a code snippet from the VSCode extension official tutorial:
let disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World!');
});
context.subscriptions.push(disposable);
but this by itself seems to work just fine:
vscode.commands.registerCommand('extension.helloWorld', () => {
vscode.window.showInformationMessage('Hello World!');
});
Also, I tried disabling extensions that do and don't add their registered commands to context.subscriptions
-- commands were unavailable after disabling in both cases.
The VS Code Api Reference defines subscriptions
as:
subscriptions: {dispose}[]
An array to which disposables can be added. When this extension is deactivated the disposables will be disposed.
Does this mean that if registered commands are NOT disposed of, then their listeners hang around somehow even after the extension is closed?
TDLR - Should I subscribe my commands or not, and why?
Any explanations or insights would be appreciated!
Yes, you should add your command to subscriptions
. The subscription ensures that your command is properly de-registered when your extension is unloaded.
vscode.commands.registerCommand
returns a disposable object. Disposing of the returned object un-registers the command, allowing VS Code to clean up any internal state/handles it may have for it.
In short, all disposable objects that your extension creates should go into subscriptions
in some way so that they can be properly cleaned up when your extension is unloaded. Failing to register a disposable may not cause obvious problems for users 99% of the time, but could cause issues in cases like when users enable and disable your extension without restarting vscode
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With