Skip to content

Instantly share code, notes, and snippets.

@piyushgarg-dev
Created June 13, 2020 07:38
Show Gist options
  • Save piyushgarg-dev/8dcf9e2c6d2c52798a27b87614648dd8 to your computer and use it in GitHub Desktop.
Save piyushgarg-dev/8dcf9e2c6d2c52798a27b87614648dd8 to your computer and use it in GitHub Desktop.
type Subscriber<T> = (val: T) => void;
type Unsubscribe = () => void;
export class Observable<T> {
private _val: T;
private _listners: Array<Subscriber<T>>;
constructor() {
this._listners = [];
}
set(val: T) {
this._val = val;
this._listners.forEach(e => e(val));
}
get(): T {
return this._val;
}
subscribe(e: Subscriber<T>): Unsubscribe {
this._listners.push(e);
return () => this._listners = this._listners.filter(el => e!==el);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment