Skip to content

Observer Pattern ​

observableObserver.ts ​

ts
interface IObserver {
  id: symbol;
  name: string;
  update(data: string): void;
}

class Observable {
  private observers: IObserver[] = [];

  subscribe(observer: IObserver) {
    this.observers.push(observer);
  }

  unsubscribe(observer: IObserver) {
    this.observers = this.observers.filter(obs => obs.id !== observer.id);
  }

  notify(data: string) {
    this.observers.forEach(obs => obs.update(data));
  }
}

class Observer implements IObserver {
  id: symbol;
  name: string;

  constructor(name: string) {
    this.id = Symbol(name);
    this.name = name;
  }

  update(data: string) {
    console.log(`${this.name} has been notified: ${data}`);
  }
}

const pokedexObservable = new Observable();

const pikachuObs = new Observer("Pikachu");
const eeveeObs = new Observer("Eevee");

pokedexObservable.subscribe(pikachuObs);
pokedexObservable.subscribe(eeveeObs);

pokedexObservable.notify("Hi!");
/*
 * Pikachu has been notified: Hi!
 * Eevee has been notified: Hi!
 */

pokedexObservable.unsubscribe(pikachuObs);

pokedexObservable.notify("Hi!");
// Eevee has been notified: Hi!

Released under the MIT License.