diff --git a/spec/subjects/behavior-subject-spec.js b/spec/subjects/behavior-subject-spec.js index 6ebb4b9990..def074d23f 100644 --- a/spec/subjects/behavior-subject-spec.js +++ b/spec/subjects/behavior-subject-spec.js @@ -4,6 +4,7 @@ var Rx = require('../../dist/cjs/Rx'); var BehaviorSubject = Rx.BehaviorSubject; var nextTick = Rx.Scheduler.nextTick; var Observable = Rx.Observable; +var ObjectUnsubscribedError = Rx.ObjectUnsubscribedError; describe('BehaviorSubject', function () { it('should extend Subject', function (done) { @@ -12,6 +13,23 @@ describe('BehaviorSubject', function () { done(); }); + it('should throw if it has received an error and getValue() is called', function () { + var subject = new BehaviorSubject(null); + subject.error(new Error('derp')); + expect(function () { + subject.getValue(); + }).toThrow(new Error('derp')); + }); + + it('should throw an ObjectUnsubscribedError if getValue() is called ' + + 'and the BehaviorSubject has been unsubscribed', function () { + var subject = new BehaviorSubject('hi there'); + subject.unsubscribe(); + expect(function () { + subject.getValue(); + }).toThrow(new ObjectUnsubscribedError()); + }); + it('should have a getValue() method to retrieve the current value', function () { var subject = new BehaviorSubject('staltz'); expect(subject.getValue()).toBe('staltz'); diff --git a/src/subject/BehaviorSubject.ts b/src/subject/BehaviorSubject.ts index a6f905d902..dbd62d44a8 100644 --- a/src/subject/BehaviorSubject.ts +++ b/src/subject/BehaviorSubject.ts @@ -1,18 +1,29 @@ import {Subject} from '../Subject'; import {Subscriber} from '../Subscriber'; import {Subscription} from '../Subscription'; +import {throwError} from '../util/throwError'; +import {ObjectUnsubscribedError} from '../util/ObjectUnsubscribedError'; export class BehaviorSubject extends Subject { + private _hasError: boolean = false; + private _err: any; + constructor(private _value: T) { super(); } getValue(): T { - return this._value; + if (this._hasError) { + throwError(this._err); + } else if (this.isUnsubscribed) { + throwError(new ObjectUnsubscribedError()); + } else { + return this._value; + } } get value(): T { - return this._value; + return this.getValue(); } _subscribe(subscriber: Subscriber): Subscription { @@ -28,4 +39,9 @@ export class BehaviorSubject extends Subject { _next(value: T): void { super._next(this._value = value); } + + _error(err: any): void { + this._hasError = true; + super._error(this._err = err); + } } \ No newline at end of file