JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 123
  • Score
    100M100P100Q80084F
  • License MIT

Tiny observable library for other extensibility

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/observable

Usage

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 with next, error, and complete methods

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