disposables
Disposables let you safely compose resource disposal semantics
A tiny JavaScript library, extracted from RxJS, that reliably cleans up event listeners, connections, and subscriptions exactly once and never twice.
Disposables Explanation
This package helps you clean up resources in JavaScript — things like event listeners, DOM connections, or network sockets — in a safe and organized way. When you attach an event handler or open a connection, you eventually need to remove or close it. This library provides a few small tools to make sure that cleanup happens reliably and exactly once, without accidentally running the same cleanup code twice or forgetting to clean up some of your resources.
The package includes three main tools. The basic Disposable wraps a cleanup function and guarantees it runs only once, no matter how many times you tell it to clean up. CompositeDisposable lets you group multiple cleanups together so you can dispose of them all at once with a single call — useful when you've set up ten event handlers and want to remove them all later. SerialDisposable handles the case where you want to swap out one set of resources for another; it automatically cleans up the old ones before switching to the new set.
The real-world use case is something like a web app that attaches event listeners to DOM nodes. You might add listeners to five buttons, store the cleanup functions for each one, then put all those cleanup functions into a CompositeDisposable. When the user navigates away or the component unmounts, you call dispose() once on the composite, and all five listeners get removed. If you later need to replace those buttons with new ones, a SerialDisposable lets you safely swap out the old cleanup logic for new cleanup logic, ensuring the old listeners are removed first.
This code originated in RxJS, a popular reactive programming library, but this package extracts just the disposal logic as a tiny, standalone module. It's useful for any JavaScript project where you need to reliably manage resource cleanup — particularly in frameworks and libraries that deal with event handling, subscriptions, or lifecycle management. The README notes the package is not actively maintained and suggests newer alternatives for new projects, but the code is stable and the pattern it implements is timeless.
Where it fits
- Group multiple event listener cleanups with CompositeDisposable and remove them all with one dispose() call.
- Guarantee a cleanup function runs exactly once using the basic Disposable wrapper.
- Safely swap old resources for new ones with SerialDisposable, ensuring the old ones are disposed first.
- Manage lifecycle cleanup for subscriptions or DOM connections in a framework or library.