| 1 |
import { Subject } from './Subject'; |
| 2 |
import { Subscriber } from './Subscriber'; |
| 3 |
import { Subscription } from './Subscription'; |
| 4 |
|
| 5 |
/** |
| 6 |
* A variant of Subject that requires an initial value and emits its current |
| 7 |
* value whenever it is subscribed to. |
| 8 |
*/ |
| 9 |
export class BehaviorSubject<T> extends Subject<T> { |
| 10 |
constructor(private _value: T) { |
| 11 |
super(); |
| 12 |
} |
| 13 |
|
| 14 |
get value(): T { |
| 15 |
return this.getValue(); |
| 16 |
} |
| 17 |
|
| 18 |
/** @internal */ |
| 19 |
protected _subscribe(subscriber: Subscriber<T>): Subscription { |
| 20 |
const subscription = super._subscribe(subscriber); |
| 21 |
!subscription.closed && subscriber.next(this._value); |
| 22 |
return subscription; |
| 23 |
} |
| 24 |
|
| 25 |
getValue(): T { |
| 26 |
const { hasError, thrownError, _value } = this; |
| 27 |
if (hasError) { |
| 28 |
throw thrownError; |
| 29 |
} |
| 30 |
this._throwIfClosed(); |
| 31 |
return _value; |
| 32 |
} |
| 33 |
|
| 34 |
next(value: T): void { |
| 35 |
super.next((this._value = value)); |
| 36 |
} |
| 37 |
} |