Created
January 28, 2017 12:37
-
-
Save jamesbirtles/becf41d9d5692743933dc23e6c66aebd to your computer and use it in GitHub Desktop.
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 { Subject } from 'rxjs/Subject'; | |
import { Subscriber } from 'rxjs/Subscriber'; | |
import { ISubscription, Subscription } from 'rxjs/Subscription'; | |
import { ObjectUnsubscribedError } from 'rxjs/util/ObjectUnsubscribedError'; | |
/** | |
* MemorizingSubject acts like a BehaviorSubject, except that it is seeded | |
* with no value, calls to getValue() will fail before the first `next` call, | |
* and it does not push a value to subscribers if `next` has not been called. | |
*/ | |
export class MemorizingSubject<T> extends Subject<T> { | |
private value: T; | |
private hasSet = false; | |
public hasValue(): boolean { | |
return this.hasSet; | |
} | |
public getValue(): T { | |
if (this.hasError) { | |
throw this.thrownError; | |
} | |
if (this.closed) { | |
throw new ObjectUnsubscribedError(); | |
} | |
if (!this.hasSet) { | |
throw new Error( | |
'Attempted to call `getValue` on a MemorizingSubject' + | |
'which did not previous have its value set.', | |
); | |
} | |
return this.value; | |
} | |
public next(value: T): void { | |
this.hasSet = true; | |
super.next(this.value = value); | |
} | |
protected _subscribe(subscriber: Subscriber<T>): Subscription { // tslint:disable-line | |
const subscription = super._subscribe(subscriber); | |
if (subscription && this.hasSet && !(<ISubscription>subscription).closed) { | |
subscriber.next(this.value); | |
} | |
return subscription; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment