Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.