Created
March 26, 2019 22:32
-
-
Save tw3/b743a15686e46afe149c7b6a74cf21a8 to your computer and use it in GitHub Desktop.
Simple state management classes
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, Subject } from 'rxjs'; | |
export enum StoreState { | |
INIT, | |
LOADING, | |
READY | |
} | |
interface StoreInterface<T> { | |
value$: Observable<T>; | |
value: T; | |
setValue(newValue: T, newState?: StoreState): void; | |
} | |
export class BehaviorState { | |
state$: Observable<StoreState>; | |
private _stateSubject$: BehaviorSubject<StoreState>; | |
protected constructor(initialState: StoreState = StoreState.INIT) { | |
this._stateSubject$ = new BehaviorSubject(initialState); | |
this.state$ = this._stateSubject$.asObservable(); | |
} | |
get state(): StoreState { | |
return this._stateSubject$.getValue(); | |
} | |
setState(newState: StoreState): void { | |
this._stateSubject$.next(newState); | |
} | |
} | |
export class Store<T> extends BehaviorState implements StoreInterface<T> { | |
value$: Observable<T>; | |
private _valueSubject$: Subject<T>; | |
protected constructor(initialState?: StoreState) { | |
super(initialState); | |
this._valueSubject$ = new Subject(); | |
this.value$ = this._valueSubject$.asObservable(); | |
} | |
get value(): T { | |
return this._valueSubject$.getValue(); | |
} | |
setValue(newValue: T, newState?: StoreState): void { | |
this._valueSubject$.next(newValue); | |
if (newState) { | |
super.setState(newState); | |
} | |
} | |
} | |
export class BehaviorStore<T> extends BehaviorState implements StoreInterface<T> { | |
value$: Observable<T>; | |
private _valueSubject$: BehaviorSubject<T>; | |
protected constructor(initialValue: T, initialState?: StoreState) { | |
super(initialState); | |
this._valueSubject$ = new BehaviorSubject(initialValue); | |
this.value$ = this._valueSubject$.asObservable(); | |
} | |
get value(): T { | |
return this._valueSubject$.getValue(); | |
} | |
setValue(newValue: T, newState?: StoreState): void { | |
this._valueSubject$.next(newValue); | |
if (newState) { | |
super.setState(newState); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment