Skip to content

Instantly share code, notes, and snippets.

@SgtPooki
Created December 16, 2021 18:55
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save SgtPooki/477014cf16436384f10a68268f86255b to your computer and use it in GitHub Desktop.
Save SgtPooki/477014cf16436384f10a68268f86255b to your computer and use it in GitHub Desktop.
Typescript version of a simple Observable. This was copied from https://stackoverflow.com/a/62002044/592760, translated to TypeScript, and improved.
/**
* Modified by Russell Dempsey on 2021 DEC 15
* @see https://stackoverflow.com/a/62002044/592760
*/
type Subscriber<T> = (value: T) => void;
class Observable<T> {
private subscribers = new Set<Subscriber<T>>();
constructor(private value: T) {}
get(): T {
return this.value;
}
set(newValue: T): void {
if (this.value === newValue) return;
this.value = newValue;
this.subscribers.forEach((listener) => listener(this.value));
}
subscribe(subscriber: Subscriber<T>): () => void {
this.subscribers.add(subscriber);
return () => this.unsubscribe(subscriber); // will be used inside React.useEffect
}
unsubscribe(subscriber: Subscriber<T>): void {
this.subscribers.delete(subscriber);
}
}
export type { Subscriber };
export { Observable };
@sovanrothaa
Copy link

Thanks 🎉

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