Package Exports
- @esmj/observable
Readme
Observable
The @esmj/observable is a tiny, extensible observable library with TypeScript support.
Features
- ðŠķ Lightweight with zero dependencies
- ðĶ Works with both ESM and CommonJS
- ð Type-safe with full TypeScript support
- ð Extensible via pipe operators
- ðŊ Simple, intuitive API
Requirements
- Node.js 18+
Install
npm install @esmj/observableUsage
import { Observable, IObservable, IObserver } from '@esmj/observable';
// Object-style observer
const observer: IObserver = {
next(value) {
console.log('Received:', value);
},
error(err) {
console.error('Error:', err);
},
complete() {
console.log('Completed');
}
};
const observable: IObservable = new Observable();
// Subscribe and get subscription object
const subscription = observable.subscribe(observer);
// Emit values
observable.next('Hello world'); // log: Received: Hello world
// Unsubscribe
subscription.unsubscribe();
// Alternative: Function-style observer
const subscription2 = observable.subscribe((value) => {
console.log('Value:', value);
});API
new Observable()
Creates a new Observable instance.
pipe(...operations: ((observable) => observable)[])
Extends the observable with custom operators. Returns a new observable with the applied operations.
Example:
const customObservable = observable.pipe(
(obs) => enhanceWithLogging(obs),
(obs) => addRetryLogic(obs)
);next(...args: unknown[])
Emits values to all subscribed observers.
Parameters:
args- Values to emit to observers
error(...args: unknown[])
Notifies observers of an error and automatically unsubscribes them.
Parameters:
args- Error information to pass to observers
complete(...args: unknown[])
Signals completion to all observers and automatically unsubscribes them.
Parameters:
args- Completion values to pass to observers
subscribe(observer: IObserver): Subscription
Subscribes an observer to receive notifications.
Parameters:
observer- Observer function or object withnext,error, andcompletemethods
Returns: Subscription object with unsubscribe() method
Observer types:
// Function observer
(value) => void
// Object observer
{
next: (value) => void,
error?: (err) => void,
complete?: () => void
}unsubscribe(observer: IObserver): void
Manually removes an observer from the subscription list.
Parameters:
observer- The observer to unsubscribe
License
MIT