Last active
December 25, 2019 19:06
-
-
Save steelx/c8b74a535c83fdd4206deb0715aace14 to your computer and use it in GitHub Desktop.
Angular rxjs-behaviour-subject-store (redux alike store with Rxjs)
This file contains 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 { 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