Skip to content

Instantly share code, notes, and snippets.

@nirkaufman
Created July 20, 2020 16:56
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 nirkaufman/6e8f4a8539974b3df0cce9d1a3f83651 to your computer and use it in GitHub Desktop.
Save nirkaufman/6e8f4a8539974b3df0cce9d1a3f83651 to your computer and use it in GitHub Desktop.
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