Skip to content

Commit 33b387b

Browse files
committed
feat(BehaviorSubject): add getValue method to access value
- 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
1 parent 2e9246e commit 33b387b

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

spec/subjects/behavior-subject-spec.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,29 @@ describe('BehaviorSubject', function () {
1212
done();
1313
});
1414

15+
it('should have a getValue() method to retrieve the current value', function () {
16+
var subject = new BehaviorSubject('staltz');
17+
expect(subject.getValue()).toBe('staltz');
18+
19+
subject.next('oj');
20+
21+
expect(subject.getValue()).toBe('oj');
22+
});
23+
24+
it('should not allow you to set `value` directly', function () {
25+
var subject = new BehaviorSubject('flibberty');
26+
subject.value = 'jibbets';
27+
expect(subject.getValue()).toBe('flibberty');
28+
expect(subject.value).toBe('flibberty');
29+
});
30+
31+
it('should still allow you to retrieve the value from the value property', function () {
32+
var subject = new BehaviorSubject('fuzzy');
33+
expect(subject.value).toBe('fuzzy');
34+
subject.next('bunny');
35+
expect(subject.value).toBe('bunny');
36+
});
37+
1538
it('should start with an initialization value', function (done) {
1639
var subject = new BehaviorSubject('foo');
1740
var expected = ['foo', 'bar'];

src/subject/BehaviorSubject.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,29 @@ import {Subscriber} from '../Subscriber';
33
import {Subscription} from '../Subscription';
44

55
export class BehaviorSubject<T> extends Subject<T> {
6-
constructor(private value: any) {
6+
constructor(private _value: T) {
77
super();
88
}
99

10+
getValue(): T {
11+
return this._value;
12+
}
13+
14+
get value(): T {
15+
return this._value;
16+
}
17+
1018
_subscribe(subscriber: Subscriber<any>): Subscription<T> {
1119
const subscription = super._subscribe(subscriber);
1220
if (!subscription) {
1321
return;
1422
} else if (!subscription.isUnsubscribed) {
15-
subscriber.next(this.value);
23+
subscriber.next(this._value);
1624
}
1725
return subscription;
1826
}
1927

2028
_next(value: T): void {
21-
super._next(this.value = value);
29+
super._next(this._value = value);
2230
}
2331
}

0 commit comments

Comments
 (0)