Skip to content

Instantly share code, notes, and snippets.

@Kangaroux
Created August 17, 2021 18:43
Show Gist options
  • Save Kangaroux/13ddb5573ee0878bd53efe7bfa41d291 to your computer and use it in GitHub Desktop.
Save Kangaroux/13ddb5573ee0878bd53efe7bfa41d291 to your computer and use it in GitHub Desktop.
Observable class for typescript
/**
* Simple class for managing callable observers.
*/
export class Observable<Fn extends (...args) => any> {
private observers: Set<Fn> = new Set();
add(o: Fn): void {
this.observers.add(o);
}
remove(o: Fn): void {
this.observers.delete(o);
}
notify(...args: Parameters<Fn>) {
for (const o of this.observers) {
o(...args);
}
}
}
@Kangaroux
Copy link
Author

Kangaroux commented Aug 17, 2021

Observers are stored using a Set so adding the same observer multiple times has no effect. As per the ECMA spec, notify() will iterate through the observers in the order they were added.

// The function signature we expect when calling observable.notify()
type fn = (a: string, b: number) => void;

// A simple observer that prints its arguments
const o: fn = (a: string, b: number) => console.log(a, b);
const observable = new Observable<fn>();


observable.add(o);
observable.add(o); // does nothing
observable.notify("helloworld", 1234);  // calls o once

observable.remove(o);
observable.notify("helloworld", 1234);  // does not call o

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment