Skip to content

Commit

Permalink
feat(BehaviorSubject): now throws when getValue is called after unsub…
Browse files Browse the repository at this point in the history
…scription

related #758
  • Loading branch information
benlesh committed Dec 8, 2015
1 parent 39836af commit 1ddf116
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
18 changes: 18 additions & 0 deletions spec/subjects/behavior-subject-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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');
Expand Down
20 changes: 18 additions & 2 deletions src/subject/BehaviorSubject.ts
Original file line number Diff line number Diff line change
@@ -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<T> extends Subject<T> {
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<any>): Subscription<T> {
Expand All @@ -28,4 +39,9 @@ export class BehaviorSubject<T> extends Subject<T> {
_next(value: T): void {
super._next(this._value = value);
}

_error(err: any): void {
this._hasError = true;
super._error(this._err = err);
}
}

0 comments on commit 1ddf116

Please sign in to comment.