Friday 28 February 2020

TypeScript and Observables

I have been wanting to grasp the idea of Observables and use them in my work.

Observables can be used to build a notification system, for example when something changes you can let others know.

After reading a few articles and not getting it, I got my hands dirty with code.
I only understand if I play with code.

I should not use code I do not understand.

In essence, an Observable is just a function that emits a value.

We store a set of subscribers on the Observable, and when it fires, all subscribers are notified via the Observable next function.

When we fire the Observable, it will look up all its subscribers and let them know via their Observer next functions.

In the example I played with, there are two classes.
Observable and Observer.

One instance of Observable is created.

Three instances of Observer are created. Apple, Orange, and Grape.
Observers are subscribed to the Observable.
Grape Observer is unsubscribed from the Observable.

Observable is fired to pass a message onto its Observer subscribers.


class Observable {
 observers: Array<Observer> = new Array();

 next(data: string) {
  if (this.observers.length > 0) {
   this.observers.forEach(observer => {
    observer.next(data);
   });
  }
 }

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

 unsubscribe(observer: Observer) {
  this.observers = this.observers.filter(filteredObserver => {
   return filteredObserver !== observer;
  });
 }
}

class Observer {
 name: string;

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

 next(data: string) {
  console.log(`${this.name} = ${data}`);
 }
}

let myObservable = new Observable();

let myObserver1 = new Observer('Observer Apple');
let myObserver2 = new Observer('Observer Orange');
let myObserver3 = new Observer('Observer Grape');

myObservable.subscribe(myObserver1);
myObservable.subscribe(myObserver2);
myObservable.subscribe(myObserver3);

myObservable.unsubscribe(myObserver3);

myObservable.next('Pass this message to the observer');


The output after firing the Observable.

Observer Apple = Pass this message to the observer 
Observer Orange = Pass this message to the observer


No comments:

Post a Comment