What does `toDispose.push()` do?

In trying to learn the internals of Theia, I’ve come across lines of code like this:

        const watcher = this.fileService.watch(fileUri);

What exactly is the purpose of toDispose? I see it wherever events are used, and my guess is it has something to do with memory management, but I’m wondering in what situations should I be using this?

@bendavis in general it is used to dispose of listeners (such as event listeners) so they are not dangling and do not cause memory leaks. It is also use to dispose of listeners under certain conditions, such as when an active editor is closed and we do not want to listen to it anymore (example).

Some additional references:


It is a cleanup mechanism for when something is being “disposed” and should no longer be used by any logic. It’s a design pattern we use in places where it makes sense, not everything has to be disposable, it only depends on how a feature and components are designed. Example: Singletons usually shouldn’t be disposables, but they might handle disposables getting created and disposed.

TL;DR this is for resource management in general, not only memory.