Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I receive notifications when Rxjs Subject is subscribed to / unsubscribed from

I'm trying to use Rxjs as a way to manage garbage collection in a large state tree.

How can I create an operator that takes a callback function that is triggered every time the number of subscribers to the observable alters?

like image 811
Peter Morris Avatar asked Sep 15 '17 14:09

Peter Morris


People also ask

What does it mean to unsubscribe in RxJS?

Due to the RxJS architecture an observable source can implement any cleanup logic whenever unsubscribe is called. For example, when RxJS is used in the context of a Node.js application you can model file reading using observable streams. Unsubscribing in this scenario would mean releasing the file handle. When unsubscribing is not required

What is a subject in RxJS?

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers.

When should you subscribe to RxJS?

The answer to that question is, “Only when you absolutely have to.” Because (among other reasons) if you don’t subscribe, you don’t have to unsubscribe. RxJS in Angular: When To Subscribe? (Rarely) When should you subscribe? The answer to that question is, “Only when you absolutely have to.”

What is an observable source in RxJS?

Due to the RxJS architecture an observable source can implement any cleanup logic whenever unsubscribe is called. For example, when RxJS is used in the context of a Node.js application you can model file reading using observable streams.


1 Answers

Multiple ways, all involve hiding your subject and giving consumers a wrapped observable:

Want to know when something subscribes to your subject?

const subject = new Subject();
const observable = Observable.defer(() => {
  someoneJustSubscribed();
  return subject;
});
return observable;

Want to know when someone unsubscribes?

const subject = new Subject();
const observable = subject.finally(() => someoneJustUnsubscribed());
return observable;

Want to know both?

const subject = new Subject();
const observable = Observable.create(observer => {
    someoneJustSubscribed();
    const sub = subject.subscribe(observer);
    return () => {
        someoneJustUnsubscribed();
        sub.unsubscribe();
    }
});
return observable;
like image 51
Brandon Avatar answered Oct 20 '22 18:10

Brandon