Skip to content

Instantly share code, notes, and snippets.

@denismaster
Created October 26, 2018 14:49
Show Gist options
  • Save denismaster/3b1b512a6048144dc4549096c11ab7de to your computer and use it in GitHub Desktop.
Save denismaster/3b1b512a6048144dc4549096c11ab7de to your computer and use it in GitHub Desktop.
Observable Store service
import { Observable, BehaviorSubject } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
export class Store<T> {
state$: Observable<T>;
private _state$: BehaviorSubject<T>;
protected constructor(initialState: T) {
this._state$ = new BehaviorSubject(initialState);
this.state$ = this._state$
.asObservable()
.pipe(distinctUntilChanged())
}
get state(): T {
return this._state$.getValue();
}
setState(nextState: T): void {
this._state$.next(nextState);
}
patchState(patch: any): void {
const nextState: T = Object.assign({}, this.state, patch);
this._state$.next(nextState);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment