0

I want to find an observable,subject or event emitter replacement which supports one and only one subscription at any given time. i.e. the first one to get a subscription will have the right to execute its subscribe's body and when it unsubscribes itself then any next subscriber would be allowed to proceed.

Is there currently any method inside observable, subject or event emitter which supports this functionality or a replacement available which can allow this behavior.

Alternatively if there is some technique with which I can perform some functionality when ever some one subscribes/unsubscribes from our target emitter then I can perform this functionality using access modifier and a boolean.

Currently I am trying something like this:

  private OpenDialogEmitter = new EventEmitter();
  private isFirstFetch: boolean = true;




getDialogEmitter(): EventEmitter<{}> {

    if (this.isFirstFetch) {
      this.isFirstFetch = false;
      return this.OpenDialogEmitter;
    }
    return null;
  }


setFirstFetch(){
      this.isFirstFetch = true;
}

When ever some one unsubscribes it has to mark observable available again by calling setFirstFetch() method inside service.

Is there any better and built in approach?

Saif
  • 1,745
  • 5
  • 23
  • 46
  • I thought rxjs was React, not angular? – rrd Jul 26 '17 at 08:02
  • rxjs: library is available in Angular, not sure whether its available for React or not. – Saif Jul 26 '17 at 08:04
  • 1
    RxJS is an independent library. Indeed, [its only dependency](https://github.com/ReactiveX/rxjs/blob/5.4.2/package.json#L208-L210) is a small polyfill for the observable symbol. – cartant Jul 26 '17 at 08:11
  • 1
    Also, you should reconsider using Angular's `EventEmitter` in that way; it's not recommended. See [this answer](https://stackoverflow.com/a/36076701/6680611). – cartant Jul 26 '17 at 08:14

1 Answers1

2

It's hard to tell why you need this because there're operators such as share that make sure you'll always have only one subscription to the source Observable.

Since EventEmitter extends the Subject class you can check whether it has any subscriptions with the following (see https://github.com/ReactiveX/rxjs/blob/master/src/Subject.ts#L28):

const source = new Subject();

...

if (source.observers.length > 0) {
  ...
}

If you want to perform some action on subscription/unsubscription you can use Observable.defer() and add a custom tear down functions to the Subscription object with the add() method:

const source = new Subject();

const o = Observable.defer(() => {
  console.log('subscription');
  return source; // or you can create the source inside this function if you want.
});

const subscription = o.subscribe(...);

subscription.add(() => {
  console.log('unsubscription');
});
martin
  • 93,354
  • 25
  • 191
  • 226