Skip to content

Instantly share code, notes, and snippets.

@shovon
Last active March 28, 2022 04:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shovon/4e718ebba1c3c50400bc6d6de0c3f82e to your computer and use it in GitHub Desktop.
Save shovon/4e718ebba1c3c50400bc6d6de0c3f82e to your computer and use it in GitHub Desktop.
export type Listener<T> = (value: T) => void;
export type OperatorFunction<T, V> = (
oberver: IObservable<T>
) => IObservable<V>;
export interface IObservable<T> {
subscribe(listner: Listener<T>): () => void;
}
export interface Subscriber<T> {
emit(value: T): void;
}
abstract class AObservable<T> implements IObservable<T> {
protected listeners: Listener<T>[];
subscribe(cb: (value: T) => void) {
this.listeners.push(cb);
return () => {
this.listeners = this.listeners.filter((l) => l !== cb);
};
}
}
export class Observable<T> extends AObservable<T> {
constructor(cb: (subscriber: Subscriber<T>) => void) {
super();
cb({
emit: (value: T) => {
for (const listener of this.listeners) {
listener(value);
}
},
});
}
}
export class Subject<T> extends AObservable<T> implements Subscriber<T> {
emit(value: T) {
for (const listener of this.listeners) {
listener(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment