Last active
July 20, 2020 14:29
-
-
Save davidhenley/26b0c03f857e3f2de2402e9785ae0efa to your computer and use it in GitHub Desktop.
State with RxJS
This file contains hidden or 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 { 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