Skip to content

Instantly share code, notes, and snippets.

@davidhenley
Last active July 20, 2020 14:29
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 davidhenley/26b0c03f857e3f2de2402e9785ae0efa to your computer and use it in GitHub Desktop.
Save davidhenley/26b0c03f857e3f2de2402e9785ae0efa to your computer and use it in GitHub Desktop.
State with RxJS
import { Observable, BehaviorSubject } from 'rxjs';
import { distinctUntilChanged, pluck } from 'rxjs/operators';
export interface Todo {
text: string;
complete: boolean;
}
export interface State {
todos: Todo[];
}
const initialState: State = {
todos: []
}
export class Store {
private subject = new BehaviorSubject<State>(initialState);
private store = this.subject.asObservable().pipe(distinctUntilChanged());
private get value() {
return this.subject.getValue();
}
set(name: keyof State, state: any) {
this.subject.next({ ...this.value, [name]: state });
}
select(name: keyof State): Observable<any> {
return this.store.pipe(pluck(name));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment