a63d3cec0c4982e957bd1cd4ab273bbe6cdb5fd3f0e1eee35a56e17a73fabcdd6838a26afd811924cbcc5b46e1b7aba3abe351dcac2f4f219c2a7b6c63d32e 880 B

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