Skip to content

Commit

Permalink
feat: All subjects now have an observed property. This will allow u…
Browse files Browse the repository at this point in the history
…sers 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 <ben@benlesh.com>
  • Loading branch information
bbarry and benlesh committed May 21, 2021
1 parent f7ea211 commit f47425d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions api_guard/dist/types/index.d.ts
Expand Up @@ -392,6 +392,7 @@ export declare class Subject<T> extends Observable<T> implements SubscriptionLik
closed: boolean;
hasError: boolean;
isStopped: boolean;
get observed(): boolean;
observers: Observer<T>[];
thrownError: any;
constructor();
Expand Down
24 changes: 24 additions & 0 deletions spec/Subject-spec.ts
Expand Up @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions src/internal/Subject.ts
Expand Up @@ -91,6 +91,10 @@ export class Subject<T> extends Observable<T> implements SubscriptionLike {
this.observers = null!;
}

get observed() {
return this.observers?.length > 0;
}

/** @internal */
protected _trySubscribe(subscriber: Subscriber<T>): TeardownLogic {
this._throwIfClosed();
Expand Down

0 comments on commit f47425d

Please sign in to comment.