From f47425d349475231c0f3542bb6ecef16a63e933a Mon Sep 17 00:00:00 2001 From: Bill Barry Date: Fri, 21 May 2021 13:37:23 -0400 Subject: [PATCH] feat: All subjects now have an `observed` property. This will allow users to check whether a subject has current subscribers without us allowing access to the `observers` array, which is going to be made private in future versions. (#6405) * feat(Subject): add isObserved() api * fix(Subject): typo, remove done from sync test * feat(subject): change observed method to property * chore: update api_guardian files Co-authored-by: Ben Lesh --- api_guard/dist/types/index.d.ts | 1 + spec/Subject-spec.ts | 24 ++++++++++++++++++++++++ src/internal/Subject.ts | 4 ++++ 3 files changed, 29 insertions(+) diff --git a/api_guard/dist/types/index.d.ts b/api_guard/dist/types/index.d.ts index 24ba35fb29..4c34cc78a3 100644 --- a/api_guard/dist/types/index.d.ts +++ b/api_guard/dist/types/index.d.ts @@ -392,6 +392,7 @@ export declare class Subject extends Observable implements SubscriptionLik closed: boolean; hasError: boolean; isStopped: boolean; + get observed(): boolean; observers: Observer[]; thrownError: any; constructor(); diff --git a/spec/Subject-spec.ts b/spec/Subject-spec.ts index 2691c6421c..1f82ee6a87 100644 --- a/spec/Subject-spec.ts +++ b/spec/Subject-spec.ts @@ -430,6 +430,30 @@ describe('Subject', () => { done(); }); + it('should expose observed status', () => { + const subject = new Subject(); + + expect(subject.observed).to.equal(false); + + const sub1 = subject.subscribe(function (x) { + //noop + }); + + expect(subject.observed).to.equal(true); + + const sub2 = subject.subscribe(function (x) { + //noop + }); + + expect(subject.observed).to.equal(true); + sub1.unsubscribe(); + expect(subject.observed).to.equal(true); + sub2.unsubscribe(); + expect(subject.observed).to.equal(false); + subject.unsubscribe(); + expect(subject.observed).to.equal(false); + }); + it('should have a static create function that works', () => { expect(Subject.create).to.be.a('function'); const source = of(1, 2, 3, 4, 5); diff --git a/src/internal/Subject.ts b/src/internal/Subject.ts index 57f5d9d42a..0fef20a6d7 100644 --- a/src/internal/Subject.ts +++ b/src/internal/Subject.ts @@ -91,6 +91,10 @@ export class Subject extends Observable implements SubscriptionLike { this.observers = null!; } + get observed() { + return this.observers?.length > 0; + } + /** @internal */ protected _trySubscribe(subscriber: Subscriber): TeardownLogic { this._throwIfClosed();