๐ญ
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();
createObservable
API 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);