https://github.com/hediet/vscode-observables.git
A lightweight, fine-grained reactive programming library for building observable state management. Originally developed for Visual Studio Code.
This monorepo contains:
npm install @vscode/observables
For React integration:
npm install @vscode/observables @vscode/observables-react
import { observableValue, derived, autorun } from '@vscode/observables';
// Create an observable value
const count = observableValue('count', 0);
// Create a derived observable
const doubled = derived('doubled', reader => {
return count.read(reader) * 2;
});
// React to changes
const disposable = autorun(reader => {
console.log('Count:', count.read(reader));
console.log('Doubled:', doubled.read(reader));
});
// Update the value
count.set(5, undefined);
// Logs: Count: 5, Doubled: 10
// Cleanup
disposable.dispose();
Batch multiple changes to avoid intermediate updates:
import { observableValue, transaction } from '@vscode/observables';
const firstName = observableValue('firstName', 'John');
const lastName = observableValue('lastName', 'Doe');
// Both changes are applied atomically
transaction(tx => {
firstName.set('Jane', tx);
lastName.set('Smith', tx);
});
import { observableValue } from '@vscode/observables';
import { useObservable } from '@vscode/observables-react';
const count = observableValue('count', 0);
function Counter() {
const value = useObservable(count);
return (
<button onClick={() => count.set(value + 1, undefined)}>
Count: {value}
</button>
);
}
Note: React Strict Mode is not supported by @vscode/observables-react.
npm install
npm run build
npm run dev -w example-observables-react
observableValue(name, initialValue) - Create a settable observablederived(name, computeFn) - Create a computed observableconstObservable(value) - Create a constant observableautorun(fn) - Run a function whenever observed values changerunOnChange(observable, callback) - React to specific observable changestransaction(fn) - Batch multiple updateswaitForState(observable, predicate) - Await a specific stateMIT - see LICENSE