jrx
v0.4.0
Published
A lightweight TypeScript library for managing side effects, subscriptions, and animations with automatic cleanup using the [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management) API.
Readme
jrx
A lightweight TypeScript library for managing side effects, subscriptions, and animations with automatic cleanup using the Explicit Resource Management API.
Prerequisites
This library requires the Explicit Resource Management globals (DisposableStack, AsyncDisposableStack, Symbol.dispose, Symbol.asyncDispose). If your environment does not support them natively, you must load a polyfill before importing jrx (e.g. core-js).
The using keyword is not required — this library only uses the API objects directly, so no transpiler support for using declarations is needed.
Installation
npm i jrxFeatures
- Automatic cleanup for all effects and subscriptions
- Built on the native
DisposableStack/AsyncDisposableStackAPI - Zero dependencies
- Composable reactive utilities
- Browser and Node.js compatible
API Overview
makeReset()- Create a resettableDisposableStackmakeAsyncReset()- Create a resettableAsyncDisposableStackmakeRenderLoop()- Render loops with automatic cleanupcreateInterval(cb, ms)- Repeating intervals with cleanupcreateIntervalAsync(cb, ms)- Async intervals with cancellationcreateAnimationFrame(cb)- Single animation frame with cleanupcreateAnimationFrameLoop(cb)- Animation frame loopscreateTimeout(cb, ms)- Timeouts with cleanupcreateTransition(cb, durationMs)- Progress-based animationsassignDispose(value, disposable)- Attach aSymbol.disposeto any valueassignDisposeAsync(value, disposable)- Attach aSymbol.asyncDisposeto any value
Naming convention
Functions prefixed with create* return a Disposable object. The returned object can be passed to DisposableStack.use() or bound with the using keyword for automatic cleanup.
import {createInterval, createTimeout} from 'jrx'
// With DisposableStack.use()
using stack = new DisposableStack()
stack.use(createInterval(() => console.log('tick'), 1000))
stack.use(createTimeout(() => console.log('done'), 5000))
// Both are disposed when `stack` goes out of scope
// Or directly with `using`
using interval = createInterval(() => console.log('tick'), 1000)
// Disposed when the enclosing block exitsAPI
makeReset()
Creates a resettable DisposableStack. Each call disposes the previous stack and returns a new one.
import {makeReset} from 'jrx'
const reset = makeReset()
const stack = reset() // Get a fresh DisposableStack
// Add disposables
stack.use(someDisposable)
// Reset - disposes previous stack, returns new one
const newStack = reset()If a cleanup of the previous stack calls reset() itself, the stack of that call is the one in use. The outer call returns a stack that is disposed already: check stack.disposed before using it. If a cleanup throws, reset() throws after every cleanup was called, and the next reset() works as usual.
makeAsyncReset()
Async version of makeReset using AsyncDisposableStack.
import {makeAsyncReset} from 'jrx'
const reset = makeAsyncReset()
const stack = await reset() // Get a fresh AsyncDisposableStackCalls of reset() that overlap run one at a time, in the order they were made: a call disposes the stack of the call before it, and waits for that. So a call that was overtaken by a later one may return a stack that is disposed already: check stack.disposed before using it. A cleanup must not wait for a reset() call that was made after the one that disposes it: the two would wait for each other.
makeRenderLoop()
Creates a render loop with automatic cleanup management.
import {makeRenderLoop} from 'jrx'
const {loop, setLoop} = makeRenderLoop()
// Set the loop function - returns a Disposable
const handle = setLoop(time => {
console.log('Frame time:', time)
// Optional: return a Disposable for cleanup
return {
[Symbol.dispose]() {
console.log('Cleanup previous frame')
},
}
})
// Call loop on each animation frame
requestAnimationFrame(loop)
// Cleanup
handle[Symbol.dispose]()setLoop() replaces the loop function that was set before. The handle of a loop function that was replaced does nothing: only the handle of the loop function that is set unsets it. If the loop function or a cleanup throws, loop() throws that error, and the next loop() works as usual.
createInterval(cb, ms)
Creates a repeating interval with cleanup. The callback can optionally return a Disposable that is disposed before the next invocation. Returns a Disposable.
Note: The callback fires immediately on first call, then waits ms milliseconds after the previous callback completes. This is not a fixed-rate timer.
import {createInterval} from 'jrx'
const handle = createInterval(() => {
console.log('Tick') // Called immediately, then every 1000ms after completion
// Optional: return a Disposable for cleanup
return {
[Symbol.dispose]() {
console.log('Cleanup')
},
}
}, 1000)
// Stop the interval
handle[Symbol.dispose]()createIntervalAsync(cb, ms)
Async version of createInterval. Waits for the callback to complete before scheduling the next invocation. Returns a Disposable.
Note: The callback fires immediately on first call, then waits ms milliseconds after the previous async callback completes.
import {createIntervalAsync} from 'jrx'
const handle = createIntervalAsync(async () => {
// Called immediately, then 5000ms after each completion
await fetchData()
processData()
}, 5000)
handle[Symbol.dispose]()createAnimationFrame(cb)
Executes a callback on the next animation frame with cleanup. Returns a Disposable.
import {createAnimationFrame} from 'jrx'
const handle = createAnimationFrame(now => {
updateAnimation(now)
// Optional: return a Disposable for cleanup
return {
[Symbol.dispose]() {
cleanupAnimation()
},
}
})
// Cancel if needed before the frame fires
handle[Symbol.dispose]()createAnimationFrameLoop(cb)
Creates a continuous requestAnimationFrame loop with cleanup. Returns a Disposable.
import {createAnimationFrameLoop} from 'jrx'
const handle = createAnimationFrameLoop(now => {
updateAnimation(now)
// Optional: return a Disposable for cleanup
return {
[Symbol.dispose]() {
cleanupAnimation()
},
}
})
// Stop the loop
handle[Symbol.dispose]()createTimeout(cb, ms)
Creates a timeout with cleanup. Returns a Disposable.
import {createTimeout} from 'jrx'
const handle = createTimeout(() => {
console.log('Timeout fired')
}, 1000)
// Cancel if needed
handle[Symbol.dispose]()createTransition(cb, durationMs)
Creates an animation transition with progress tracking (0 to 1). Returns a Disposable.
import {createTransition} from 'jrx'
const handle = createTransition(progress => {
element.style.opacity = progress.toString()
// Optional: return a Disposable for cleanup
return {
[Symbol.dispose]() {
console.log('Frame cleanup')
},
}
}, 1000)
handle[Symbol.dispose]()assignDispose(value, disposable)
Attaches a Symbol.dispose to an existing value (object, function, array, promise, etc.) that delegates to a given Disposable. Returns the same value, now also typed as Disposable.
This is useful when a function needs to return a meaningful value and be disposable — for example, returning a promise, a function, or a tuple from a factory while still allowing the caller to clean up the underlying resources.
import {assignDispose} from 'jrx'
function makeThing() {
using stack = new DisposableStack()
stack.defer(() => console.log('cleanup'))
const obj = {value: 42}
return assignDispose(obj, stack.move())
}If value is itself a Disposable, disposing the returned value disposes value first, then disposable. disposable is disposed even if the dispose of value throws. The error is thrown after both, as a DisposableStack reports it: a SuppressedError when both threw.
assignDisposeAsync(value, disposable)
Like assignDispose, but takes an AsyncDisposable and attaches a Symbol.asyncDispose instead. Disposal is awaited — use this whenever cleanup is asynchronous and the value will be released with await using or AsyncDisposableStack.use().
import {assignDisposeAsync} from 'jrx'
function loadThing() {
const stack = new AsyncDisposableStack()
return assignDisposeAsync(
(async () => {
const res = await fetch('/api/data', {signal: stack.adopt(new AbortController(), c => c.abort()).signal})
return await res.json()
})(),
stack,
)
}
{
await using thing = loadThing()
console.log(await thing)
} // stack is awaited hereIf value has its own Symbol.asyncDispose, it is awaited first, then the disposable. The disposable is disposed even if the dispose of value rejects. The error comes after both, as an AsyncDisposableStack reports it: a SuppressedError when both rejected.
Pick the variant that matches your cleanup:
assignDisposeattaches onlySymbol.dispose(sync, use withusing),assignDisposeAsyncattaches onlySymbol.asyncDispose(async, use withawait using). Each attaches a single symbol so the type system steers you to the correct disposal form.
Cleanup Pattern
All effect functions return a Disposable object that stops the effect and runs any pending cleanup:
import {createInterval, createTimeout, createAnimationFrame, createTransition} from 'jrx'
// Each function returns a Disposable
const interval = createInterval(() => console.log('tick'), 1000)
const timeout = createTimeout(() => console.log('timeout'), 5000)
const raf = createAnimationFrame(now => render(now))
const transition = createTransition(p => console.log(p), 1000)
// Call [Symbol.dispose]() to stop the effect
interval[Symbol.dispose]()
timeout[Symbol.dispose]()
raf[Symbol.dispose]()
transition[Symbol.dispose]()Callbacks that dispose or throw
A callback (cb, or the loop function of makeRenderLoop) and the cleanup it returns may dispose the handle of their own effect, and may throw. This is what happens then:
- A callback disposes its own handle: the effect stops, and the cleanup that this call returns is called right away.
- A cleanup disposes the handle of its effect: the effect stops. The callback is not called again.
- A cleanup throws while the handle is disposed: the dispose of the handle throws that error. The effect is stopped all the same.
- A callback or a cleanup throws while the effect runs: that call ends there, and nothing is scheduled after it. The effect is over, and its handle still disposes what is left. The error goes to the code that called the callback:
createInterval: the first call is made bycreateInterval()itself, which throws the error and returns no handle. A later call is made by the timer, so the error is uncaught.createIntervalAsync: the error is an unhandled rejection, in the first call as well. So is a promise ofcbthat rejects.createAnimationFrame,createAnimationFrameLoop,createTransition: the call is made by the frame, so the error is uncaught.makeRenderLoop:loop()throws the error. This one is not over: the nextloop()calls the loop function again.
Catch errors inside the callback to keep an effect running.
TypeScript
This library is written in TypeScript and uses the Explicit Resource Management types (Disposable, DisposableStack, AsyncDisposableStack).
License
MIT
Repository
https://github.com/tranvansang/jrx
