reactive-observable
TypeScript icon, indicating that this package has built-in type declarations

1.2.2 • Public • Published

reactive-observable

Quality Gate Status Coverage Bugs min-size-g-zip dependency-count npm-version ts-types

This is a small a lightweight package implementing the observable pattern.

Installation

npm install reactive-observable

Usage

class Service {
  public myCounter = new Observable(0);

  private myInternalLogic() {
    /*
     * the goal is to exctract all logic from the ui class to the service layer
     * so the service updates the counter internally. e. g. if a timout occurrs
     */

    const currentCount = this.myCounter.get();
    this.myCounter.update(currentCount + 1);
  }
}

class Ui {
  private readonly service: Service

  constructor() {
    this.service = new Service();
    this.service.myCounter.subscribe((count) => this.render(count));
  }

  private render(count: number) {
    return `<h1>Count: ${count}</h1>`;
  }
}

Advanced Usage

It's also possible to watch object and update and subscribe to partial properties of an object.

import { Subscription } from "./Observable";

class CarService {
  public observableCar = new Obs({color: 'red', fuel: 100}); // alias for Observable

  public drive() {
    const currentFuel = this.observableCar.get().fuel
    this.observableCar.updatePartial({fuel: currentFuel - 1})
  }
}

class CarUi {
  private readonly service: CarService
  private subscription?: Subscription

  constructor() {
    this.service = new CarService();
    this.subscription = this.service.observableCar.subscribe(this.render, 'fuel');
  }

  private onUnMount() {
    this.service.observableCar.removeSubscription(this.render) // or this.subscription?.remove();
  }

  private render(fuel: number) {
    return `<h1>Fuel: ${fuel}</h1>`;
  }
}

Package Sidebar

Install

npm i reactive-observable

Weekly Downloads

9

Version

1.2.2

License

ISC

Unpacked Size

8.17 kB

Total Files

8

Last publish

Collaborators

  • mrcwbr