RxJS subscribe to change in subscribers count

228 views Asked by At

Problem: I'm using Subject observable to pass String data between components (that are too far apart in the hierarchy). I would like to be able to tell how many subscribers there are to the Subject when a component subscribes or unsubscribes. How can above be achieved? Sorry I'm new to RxJS.

Backstory: I have a simple search/filter field at the top (navbar). The main view displays a component, some components are searchable, other are not. Each searchable component subscribes to the search/filter (via service). I would like to hide search/filter field when there are no subscribers and display when there is at least one subscriber.

I know the above logic can be archived via routes, but I would like to do it via observable count.

1

There are 1 answers

0
Simplicity's_Strength On

The BehaviorSubject class from Rxjs exposes an array of observers that you can query to get the number of observers.

let obs: BehaviorSubject<string> = new BehaviorSubject("Something");
console.log(obs);
obs.subscribe(() => {
  console.log("Subscriber 1");
});
obs.subscribe(() => {
  console.log("Subscriber 2");
});
console.log(obs.observers.length);
obs.next("Something else");

Stackblitz example here