SimplGy
SimplGy

Reputation: 20437

Do something if RxJs subject's refCount drops to zero

I'm working on a service layer that manages subscriptions.

I provide subject-backed observables to consumers like this:

const subject = new Subject();
_trackedSubjects.push(subject);
return subject.asObservable();

Different consumers may monitor the channel, so there may be several observables attached to each subject.

I'd like to monitor the count of subject.observers and if it ever drops back to 0, do some cleanup in my library.

I have looked at refCount, but this only is available on Observable.

I'd love to find something like:

subject.onObserverCountChange((cur, prev) =>
  if(cur === 0 && prev !== 0) { cleanUp(subject) }
)

Is there a way to automatic cleanup like this on a subject?

Upvotes: 1

Views: 223

Answers (1)

Oles Savluk
Oles Savluk

Reputation: 4345

Instead of using Subject - you should probably describe setup/cleanup logic when creating observable. See the example:

const { Observable } = rxjs; // = require("rxjs")
const { share } = rxjs.operators; // = require("rxjs/operators")

const eventSource$ = Observable.create(o => {
  console.log('setup');
  let i = 0
  const interval = setInterval(
    () => o.next(i++),
    1000
  );

  return () => {
    console.log('cleanup');
    clearInterval(interval);
  }
});
const events$ = eventSource$.pipe(share());

const first = events$.subscribe(e => console.log('first: ', e));
const second = events$.subscribe(e => console.log('second: ', e));

setTimeout(() => first.unsubscribe(), 3000);
setTimeout(() => second.unsubscribe(), 5000);
<script src="https://unpkg.com/[email protected]/bundles/rxjs.umd.min.js"></script>

Upvotes: 1

Related Questions