Use Best Practices for Memory and Lifecycle Management
mainTo prevent memory leaks and ensure stability, follow these lifecycle rules:
- Automatic Cleanup: Use
this.registerEvent(),this.addCommand(),this.registerDomEvent(), orthis.registerInterval()so Obsidian can manage cleanup automatically. - View Management: Do not store view references directly in your plugin class. Instead, create and return the view directly within
registerView. - Leaf Cleanup: Do not manually call
this.app.workspace.detachLeavesOfType()inonunload; let Obsidian handle the cleanup of registered leaves.
// CORRECT: Create and return directly to avoid memory leaks
this.registerView(VIEW_TYPE, (leaf) => {
return new CustomView(leaf);
});
// INCORRECT: Storing view reference in plugin
this.registerView(VIEW_TYPE, (leaf) => {
this.view = new CustomView(leaf);
return this.view;
});