Skip to content

Instantly share code, notes, and snippets.

@lacolaco
Last active November 7, 2020 23:38
Show Gist options
  • Save lacolaco/4858d86da63a0d9b716c80de48008329 to your computer and use it in GitHub Desktop.
Save lacolaco/4858d86da63a0d9b716c80de48008329 to your computer and use it in GitHub Desktop.
Simple Store with RxJS
import { distinctUntilChanged, map } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
export abstract class Store<T> extends BehaviorSubject<T> {
constructor(initialState: T) {
super(initialState);
}
public dispatch(fn: (state: T) => T) {
this.next(fn(this.getValue()));
}
public select<R>(fn: (state: T) => R) {
return this.pipe(map<T, R>(fn), distinctUntilChanged());
}
public selectSync<R>(fn: (state: T) => R) {
return fn(this.getValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment