simple-observables

Simple observable implementation for JavaScript


Keywords
observable, subscription
License
MIT
Install
npm install simple-observables@0.1.0

Documentation

GitHub license npm version Downloads GitHub issues GitHub language Minified size

Simple Observables ๐Ÿ”ญ

Idea

To have a simple JavaScript API for creating and using observable/subscription pattern, without the need of importing super-heavy libraries such as RxJS (which I personally found to be one of the best libraries ever made).

Getting Started

Installation

Via yarn:

yarn add simple-observables

Via npm:

npm install simple-observables

Usage

ES modules:

import { createObservable } from 'simple-observables';

const myObservable = createObservable();

API createObservable

Creates an observable value and returns:

  • getter - to get the current value
  • setter - to set the current value
  • subscribe - to subscribe an observer for value changes
  • unsubscribe - to unsubscribe an observer for value changes

Example

const [getAnimal, setAnimal, subscribe, unsubscribe] = createObservable();

setAnimal('๐Ÿฑ');
console.log(getAnimal()); // ๐Ÿฑ

const logAnimal = (animal) => console.log(`My current animal is: ${animal}`);
subscribe(logAnimal);

setAnimal('๐Ÿถ'); // My current animal is: ๐Ÿถ
setAnimal('๐Ÿท'); // My current animal is: ๐Ÿท
setAnimal('๐ŸฆŠ'); // My current animal is: ๐ŸฆŠ

unsubscribe(logAnimal);
console.log(getAnimal()); // ๐ŸฆŠ

API Design

  • Array destructuring is letting you name your variables:
const [getValue, setValue, subscribe, unsubscribe] = createObservable();

const [getX, setX, subscribeToX, unsubscribeToX] = createObservable();
const [getY, setY, subscribeToY, unsubscribeToY] = createObservable();
// ...
  • Multiple subscriptions support:
const [getValue, setValue, subscribe, unsubscribe] = createObservable();

const logWithA = (value) => console.log(`A: ${value}`);
const logWithB = (value) => console.log(`B: ${value}`);
// ...

subscribe(logWithA);
subscribe(logWithB);
// ...

setValue('Hello!'); /* A: Hello!
                       B: Hello! */

unsubscribe(logWithA);
unsubscribe(logWithB);
// ...
  • Initial value for observable can be provided:
const initialValue = {
  preferredGreeting: 'Ahoj',
  profession: 'Pirate',
};

const [getValue] = createObservable(initialValue);

console.log(getValue()); // { preferredGreeting: "Ahoj", profession: "Pirate" }
  • TypeScript support out of the box:
type Book = {
  name: string;
  author: string;
};

const doSomethingWithBook = (book?: Book) => {
  /* ... */
};

const bookObservable = createObservable<Book | undefined>(undefined);
const [getBook, setBook, subscribe, unsubscribe] = bookObservable;

subscribe(doSomethingWithBook);

setBook({
  name: 'The Metabarons',
  author: 'Alejandro Jodorowsky',
});

unsubscribe(doSomethingWithBook);

Code in Repository

Visualization of the codebase