Skip to content

Instantly share code, notes, and snippets.

@riapacheco
Created July 20, 2022 18:01
Show Gist options
  • Save riapacheco/74903c8c8eb9a71f7f58bc2b4c8261a3 to your computer and use it in GitHub Desktop.
Save riapacheco/74903c8c8eb9a71f7f58bc2b4c8261a3 to your computer and use it in GitHub Desktop.
State Service where all Feature State's extend from
import { BehaviorSubject, Observable } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
export class StateService {
private state$!: BehaviorSubject<any>;
protected get state(): any {
return this.state$.getValue();
}
constructor(initialState: any) {
this.state$ = new BehaviorSubject<any>(initialState);
}
protected select<K>(mapFn: (state: any) => K): Observable<K> {
return this.state$.asObservable().pipe(
map((state: any) => mapFn(state)),
distinctUntilChanged()
);
};
// Return state snapshot after merging partial state with full obj state
protected setState(newState: Partial<any>) {
this.state$.next({
...this.state,
...newState
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment