Last active
November 7, 2020 23:38
-
-
Save lacolaco/4858d86da63a0d9b716c80de48008329 to your computer and use it in GitHub Desktop.
Simple Store with RxJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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