Skip to content

Commit

Permalink
feat(BehaviorSubject): add getValue method to access value
Browse files Browse the repository at this point in the history
- adds `getValue` method to get inner value
- further hides the value as `_value`
- adds `value` property getter
- purposefully excludes `value` property setter
- adds tests around `getValue` method and `value` property

fixes #758
  • Loading branch information
benlesh committed Dec 8, 2015
1 parent 2e9246e commit 33b387b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
23 changes: 23 additions & 0 deletions spec/subjects/behavior-subject-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,29 @@ describe('BehaviorSubject', function () {
done();
});

it('should have a getValue() method to retrieve the current value', function () {
var subject = new BehaviorSubject('staltz');
expect(subject.getValue()).toBe('staltz');

subject.next('oj');

expect(subject.getValue()).toBe('oj');
});

it('should not allow you to set `value` directly', function () {
var subject = new BehaviorSubject('flibberty');
subject.value = 'jibbets';
expect(subject.getValue()).toBe('flibberty');
expect(subject.value).toBe('flibberty');
});

it('should still allow you to retrieve the value from the value property', function () {
var subject = new BehaviorSubject('fuzzy');
expect(subject.value).toBe('fuzzy');
subject.next('bunny');
expect(subject.value).toBe('bunny');
});

it('should start with an initialization value', function (done) {
var subject = new BehaviorSubject('foo');
var expected = ['foo', 'bar'];
Expand Down
14 changes: 11 additions & 3 deletions src/subject/BehaviorSubject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,29 @@ import {Subscriber} from '../Subscriber';
import {Subscription} from '../Subscription';

export class BehaviorSubject<T> extends Subject<T> {
constructor(private value: any) {
constructor(private _value: T) {
super();
}

getValue(): T {
return this._value;
}

get value(): T {
return this._value;
}

_subscribe(subscriber: Subscriber<any>): Subscription<T> {
const subscription = super._subscribe(subscriber);
if (!subscription) {
return;
} else if (!subscription.isUnsubscribed) {
subscriber.next(this.value);
subscriber.next(this._value);
}
return subscription;
}

_next(value: T): void {
super._next(this.value = value);
super._next(this._value = value);
}
}

0 comments on commit 33b387b

Please sign in to comment.