Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose for subscribing a command in vscode extension?

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!

like image 852
stuart Avatar asked Apr 06 '19 22:04

stuart


1 Answers

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

like image 184
Matt Bierner Avatar answered Nov 16 '22 22:11

Matt Bierner