Created
June 10, 2017 10:29
-
-
Save yjaaidi/ddb11579b09b4486a35d9c608d9a2bca to your computer and use it in GitHub Desktop.
Reactive Store
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 { ReplaySubject } from 'rxjs/ReplaySubject'; | |
import { Observable } from 'rxjs/Observable'; | |
export abstract class ReplayStore<T> { | |
private _isInitialized = false; | |
private _state: T; | |
private _state$: ReplaySubject<T>; | |
constructor() { | |
this._state$ = new ReplaySubject<T>(1); | |
this._state$ | |
.subscribe((state) => this._state = state); | |
} | |
get state(): T { | |
return this._state; | |
} | |
get replaySubject(): Observable<T> { | |
if (!this._isInitialized) { | |
return this._lazyInit() | |
.do((state) => this._setState(state)); | |
} | |
return this._state$.asObservable(); | |
} | |
protected abstract _lazyInit(): Observable<T>; | |
protected _setIsInitialized() { | |
this._isInitialized = true; | |
} | |
protected _setState(state: T) { | |
this._state$.next(state); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment