Created
December 18, 2019 02:05
-
-
Save mayrascript/e6184db88504939e3d83cd168a8d439e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { Injectable } from '@angular/core'; | |
| import { Action } from 'src/app/core/services/store/reducers'; | |
| import { BehaviorSubject, Subject } from 'rxjs'; | |
| import { scan } from 'rxjs/operators'; | |
| class Dispatcher<T> extends Subject<T> { | |
| dispatch(value: any): void { | |
| this.next(value); | |
| } | |
| } | |
| @Injectable({ | |
| providedIn: 'root' | |
| }) | |
| export class StoreService<T> extends BehaviorSubject<T> { | |
| private dispatcher = new Dispatcher(); | |
| constructor(private reducer, | |
| initialState) { | |
| super(initialState); | |
| // create an temp store in memory inside of observable | |
| this.dispatcher.pipe( | |
| scan((state, action) => this.reducer(state, action), initialState)) | |
| .subscribe(state => super.next(state)); | |
| } | |
| dispatch(value: Action) { | |
| this.dispatcher.dispatch(value); | |
| } | |
| next(value) { | |
| this.dispatcher.dispatch(value); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment