Skip to content

Instantly share code, notes, and snippets.

@steelx
Last active December 25, 2019 19:06
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 steelx/c8b74a535c83fdd4206deb0715aace14 to your computer and use it in GitHub Desktop.
Save steelx/c8b74a535c83fdd4206deb0715aace14 to your computer and use it in GitHub Desktop.
Angular rxjs-behaviour-subject-store (redux alike store with Rxjs)
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
export class Store<T> {
private _state$: BehaviorSubject<T>;
protected constructor(initialState: T) {
this._state$ = new BehaviorSubject(initialState);
}
get state$(): Observable<T> {
return this._state$.asObservable();
}
get state(): T {
return this._state$.getValue();
}
setState(nextState: T): void {
this._state$.next(nextState);
}
}
///////////////
// usage below
///////////////
class TestState {
testProperty: string = 'initial value';
}
class TestStore extends Store<TestState> {
constructor () {
super(new TestState());
}
updateTestProperty (): void {
this.setState({
...this.state,
testProperty: 'updated value',
});
}
}
class TestComponent {
store: TestStore;
constructor () {
this.store = new TestStore();
this.store.state$.subscribe(state => {
console.log(state);
});
setTimeout(() => {
this.store.updateTestProperty();
}, 3000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment