Created
July 20, 2020 16:56
-
-
Save nirkaufman/6e8f4a8539974b3df0cce9d1a3f83651 to your computer and use it in GitHub Desktop.
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 {BehaviorSubject, Observable} from "rxjs"; | |
import {Inject, Injectable, InjectionToken} from "@angular/core"; | |
export interface Action { | |
type: string; | |
} | |
export interface ActionHandler { | |
handleAction(currentState: any, action: Action): any; | |
} | |
export const ActionHandlers = new InjectionToken( | |
'lookup for action handlers', | |
{providedIn: 'root', factory: () => []} | |
) | |
export const InitialState = new InjectionToken( | |
'lookup for initial state', | |
{providedIn: 'root', factory: () => null} | |
) | |
@Injectable() | |
export class StateService { | |
private _state: BehaviorSubject<any>; | |
actions: BehaviorSubject<Action>; | |
state$: Observable<any>; | |
constructor(@Inject(InitialState) initialState: any, | |
@Inject(ActionHandlers) actionHandlers: ActionHandler[]) { | |
this._state = new BehaviorSubject<any>(initialState) | |
this.actions = new BehaviorSubject<Action>({type: 'init'}) | |
this.actions.subscribe(action => { | |
const nextState = this._state.getValue(); | |
actionHandlers.forEach( handler => { | |
Object.assign(nextState, handler.handleAction(nextState, action)) | |
}) | |
this._state.next(nextState); | |
}) | |
this.state$ = this._state.asObservable(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment