Restrict the number of subscriptions allowed for an rxjs observable

Seeking a replacement for observable, subject, or event emitter that allows only one subscription at a time. The first subscriber should have priority to execute its subscribe function, with subsequent subscribers waiting their turn until the first unsubscribes.

Is there an existing method within observable, subject, or event emitter that supports this behavior, or is there a replacement available that can achieve this functionality?

Alternatively, if there is a technique to detect when a subscriber subscribes or unsubscribes from our target emitter, we could implement this using access modifiers and a boolean flag.

I am currently experimenting with the following code:

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;
}

We need to call setFirstFetch() in the service whenever someone unsubscribes to make the observable available again.

Is there a more effective and built-in approach to achieving this goal?

Answer №1

Figuring out the necessity of this information can be tricky, especially when there are operators like share that ensure you only have one subscription to the source Observable at all times.

With EventEmitter being an extension of the Subject class, you can determine if it has any subscriptions by checking the following (refer to https://github.com/ReactiveX/rxjs/blob/master/src/Subject.ts#L28):

const source = new Subject();

...

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

If you need to execute certain actions upon subscription or unsubscription, you can utilize Observable.defer() and attach custom tear down functions to the Subscription object using the add() method:

const source = new Subject();

const o = Observable.defer(() => {
  console.log('subscription');
  return source; // Alternatively, you can create the source within this function if desired.
});

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

subscription.add(() => {
  console.log('unsubscription');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 - Conceal Table Panel if there is no data in the table

I am using *ngFor to generate panels that contain tables. Each table uses *ngFor to create <td> elements for each item in a dataset. Sometimes the table will have empty rows. Is there a clever way to hide the panel when the table has no children? I ...

The Angular dependency provider is failing to supply the requested alternative class

I am currently in the process of writing unit tests for the doc-manager.component component. This particular component relies on the DocService, but I want to swap it with instances of MockedDocService within my tests. By leveraging alternative class prov ...

Tips for correctly linking an Event Listener to the worldwide 'window' in Angular 6 and higher

Situation Within our Angular 6 application, an iframe is embedded to showcase third-party data. To facilitate secure cross-domain communication, the child iframe sends messages to the parent Angular app using window.postMessage() API. To receive these mes ...

The synergy between JSDoc and type mapping

I am in search of a comprehensive and reliable source that provides detailed information on how TypeScript's JSDoc interacts with types, their mappings, and modifications. It is widely known that Pick and Omit maintain the original JSDoc: const any: ...

Display a React functional component

Greetings, friends! I recently created a React app using functional components and now I am looking to print a specific page within the app. Each page is its own functional component, so I was wondering if it's possible to print a component individual ...

Firebase Authentication error code "auth/invalid-email" occurs when the email address provided is not in a valid format, triggering the message "The email address is

Currently, I am working on integrating Firebase login and registration functionality into my Angular and Ionic 4 application. Registration of user accounts and password retrieval are functioning properly as I can see the accounts in my Firebase console. Ho ...

Encountered a timeout error of 2000ms while running tests on an asynchronous function within a service

Here is the service I am working with: class MyService { myFunction(param){ return Observable.create(obs => { callsDBfunc(param, (err, res) => { if(err) obs.error(err); ...

Is seamless integration possible between Angular2 and jQuery plugins?

When attempting to integrate jQuery plugins with Angular 2, there are three distinct scenarios: 1. ONLOAD: Initializing the plugin on page load works smoothly with the following code snippet: ngAfterViewChecked(){ ... $('#somedatatable1&apos ...

Troubleshooting Electron Angular Application Connectivity Issues with API

While developing my ionic/angular app as an electron app, I encountered a problem when running it. After loading, I received the error message shown below: Refused to connect to 'https://xxxxxxxxxx.com/whpacking/v1/getlocations' because it violat ...

I'm looking for a way to implement a jQuery-style initialization pattern using TypeScript - how can I

My library utilizes a jQuery-like initialization pattern, along with some specific requirements for the types it should accept and return: function JQueryInitializer ( selector /*: string | INSTANCE_OF_JQUERY*/ ) { if ( selector.__jquery ) return select ...

Angular 2: Sending an HTTP GET request with custom headers and parameters

I have been encountering difficulties while attempting to retrieve data from a Stardog triple store into Angular. Despite successfully accessing the service using curl with matching headers and parameters, I am unable to replicate this functionality with ...

Deduce the types of parameters in nested functions based on the parent object

Having encountered a challenging obstacle in my Typescript journey, I find myself facing a dilemma with building a command-parsing utility. My aim is to incorporate type hints within configuration objects. Let's delve into the code example below; int ...

Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]** The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I wa ...

ngx-translate-multi-http-loader: An error occurred while trying to load the specified translation file

While working on my Ionic 5 App, I decided to use the library ngx-translate-multi-http-loader in order to load multiple language files. Even though there were no errors, I encountered an issue where the translations were not functioning properly. To reso ...

Using TypeScript: Union Types for Enum Key Values

Here's the code in the TS playground too, click here. Get the Enum key values as union types (for function parameter) I have managed to achieve this with the animals object by using key in to extract the key as the enum ANIMALS value. However, I am s ...

Ways to determine the present condition (Checked or Unchecked) of Angular Material Multiselect

When working with MatSelect and allowing multiple selections of items, I am seeking a way to determine the current state of an item. Specifically, I want to know if the currently clicked item is checked or unchecked, as this will determine whether or not ...

What should I do about typescript and ES6?

An error occurred while running my code: [0] app/components/people/details/PersonDetailComponent.ts(27,35): error TS2339: Property 'person' is missing from type '{}'. Here is the code snippet in question: export class PersonDeta ...

Issue with Parcel / React 18 App.js failing to refresh cache

Currently, I am developing a React application for my school project. However, I have encountered an issue where certain components are not rendering in my App.js file. Strangely, when I place these components as child components of App.js, they do render ...

Guide on transferring individual key values from an array to another array sequentially by clicking a button in Angular/JavaScript

I have an array of objects called marrayval. From this array, I want to extract the 'country' values one by one and push them into the arrayval after each click event. For example, on the first click, I would push C1, on the second click C1, C2, ...

The category has been defined but remains inaccessible. What could be the reason for this limitation?

I've been utilizing this bson library along with the corresponding declaration found here. Within this library, there is a method called serialize():Buffer which returns a Buffer. When I execute the following code: let data:Buffer = this.serializer.s ...