Tips for handling numerous observables in Angular 7

I am working on an Angular 7 application that deals with a total of 20 sensor data. My goal is to receive data from a selected sensor every 5 seconds using observables. For example:

var sensorId = ""; // dynamically chosen from the web interface
var sensorData$ = interval(5000).pipe()
sensorData$.subscribe() // etc..

I will be selecting multiple sensors and initiating data retrieval via subscription using intervals. How can I manage these observables effectively? What's the best approach to handle them?

In addition, I have the capability to add any new sensor at any given time.

Answer №1

If you're looking for a solution, I recommend utilizing Subject and mergeMap.

To elaborate, create a single Subject to emit new sensorIds when chosen by the user in the UI. Subsequently, subscribe to this Subject and utilize mergeMap within your subscription method to handle all sensor values effectively.

Let's examine a sample code snippet below:

private sensorIdSubject = new Subject();

ngOnInit() {
  this.sensorIdSubject.pipe(
    mergeMap(sensorId => 
      interval(5000).pipe(switchMap(() => this.getSensorData(sensorId)))
  ).subscribe(sensorData => {
    // At intervals of 5 seconds, retrieve data for selected sensorIds from the UI
    // and emit new values in the subscribe function as they are consolidated.
  })
}

public chooseSensor(sensorId) {
  this.sensorIdSubject.next(sensorId);
}

Does this approach align with your requirements? If modifications are necessary, feel free to provide feedback in the comments section for further adjustments.

Answer №2

To consolidate multiple observables into one and receive all the emitted values, you can utilize rxjs' forkJoin method.

This allows you to handle a group of observables collectively, enabling you to apply pipe operators and perform various operations on the combined data.

For example:

let sensors = forkJoin(observable1, observable2)

sensors.subscribe(
   sensorData => {
      // Handle the object containing data from your observables
   }
)

If you have varying numbers of observables emitting different values, consider using BehaviorSubject in the following manner:

let sensors = new BehaviorSubject<Array<Observables<yourType>>([])

sensors.next([newArrayOfObservables])

sensors.subscribe(
    sensors$ => {
      sensor$.forEach(sensor => {
        sensor.subscribe( // Perform your logic)
      }
    }
)

This approach allows for adding or removing observables dynamically. Keep in mind that ForkJoin only emits values when all observables complete, triggering only one emission event.

Lastly, remember to properly manage your unsubscriptions to avoid memory leaks.

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

Steps for setting up Angular 5 on your system

My current project requires Angular 5, but with the recent release of Angular 7, I'm unsure how to set up Angular 5 on my computer. I had transitioned from Angular 6 a few months ago. Do I need to uninstall the latest version to work with Angular 5? ...

Jest: A runtime error occurred because the property being accessed is undefined

Currently, I am testing my React class which includes the import statement import dotnetify from "dotnetify";. While this works without any issues, Jest is reporting that dotnetify is undefined. Interestingly, when I switch the import to const do ...

Animating background color change with scroll in React using fade effect

Can someone help me with implementing a fading animation for changing the background color on scroll in React? I have successfully achieved the background change effect, but I'm struggling to incorporate the fading effect. import React from "reac ...

Retrieving the value of a TextField from Material-UI upon submission

Is it possible to capture the value from a TextField input and display a message conditionally using onSubmit instead of onChange? I have tried implementing this functionality dynamically with onChange, but now I would like to achieve the same result wit ...

Unable to Render Data URI onto HTML5 Canvas

I have been attempting for quite some time and feeling frustrated. I am facing issues with my Data URI image not being able to write to my canvas for reasons unknown .... Here's the code snippet ... function addImage() { var allfiles = $("#postAtta ...

refusing to display the pop-up in a separate window

Hi there, I'm having an issue with a link that's supposed to open in a pop-up but is instead opening in a new tab. I'd like it to open in a proper pop-up window. <button class="button button1" onclick=" window.open('te ...

In search of advice on the best web-based database management technology

I'm looking to create a prototype for a web-based database manager, similar to the desktop version in the image below, with specific features in mind. Initially, the schema will be provided through a flat file. Considering HTML5 as an option, I am a ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

Tips for applying multiple style properties to an element using JavaScript

I have been experimenting with different versions of this code in an attempt to modify a specific element for a coding challenge, but none of them seem to successfully change multiple styling properties of the element upon clicking on a button. Would great ...

What are some strategies to prevent django form fields from being reset or cleared in the event of an error during submission?

I'm utilizing django's registration-redux for user registration, but I'm facing an issue. When I enter the same user ID, it displays an error and clears all the input fields on the form. How can I prevent this error from occurring without cl ...

Execute a JavaScript function when an HTML list element is clicked

As a beginner in web development, I have a question that might seem obvious to some. I want to create a menu where each item, when clicked, triggers a JavaScript function with the item's ID as an argument. I plan to display the menu items in an unorde ...

Remove the most recently played sound from an array of sound using Vue.js

I've been trying to figure out how to randomize the sounds that play when a button is clicked, but I also want to avoid repeating the last played sound. It just doesn't sound right if the same sound plays repeatedly in quick succession. I'm ...

In the readmore.js script, position the "readmore" link within a div instead of outside of it

I have added annotations that vary in length, so I am looking to integrate the readmore.js plugin. To ensure uniform sizing for all annotations (even empty ones), I need to set a minimum height for the div container. <annotation> <div style="wi ...

The point in the vector data is incorrectly positioned on the map in OpenLayers

I am looking to display a world map using the default OpenLayers WMS, along with a single point on it that will have interactive events like onhover. Below is my code snippet: var options = { projection: ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...

The horizontal scrollbar in PrimeNG's p-tree is cleverly concealed until I reach the bottom of the div and start scrolling

I'm facing an issue where the horizontal scrollbar in my p-tree component is hidden until I scroll all the way down. I've tried various CSS modifications, but nothing seems to work. It's surprising that I couldn't find anyone else with ...

Using Apache to rewrite wildcard subdomains for an Angular application

I am currently facing a challenge with my Angular app that needs to be set up under subdomains for multi-tenant support. Each subdomain represents a different tenant within the application. At present, I have an .htaccess configuration that successfully lo ...

Is the JSON data missing from the POST request?

I'm having trouble inserting data into the database using a POST request. Here is how I'm making the request: 127.0.0.1:3000/api/users?fname=asd&lname=edc&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7870 ...

What could be causing IdentityServer 4 code flow to intermittently receive an invalid_grant response?

For my Angular application, I have implemented the identityserver4 code flow using the angular-oauth2-oidc library. Here is a snippet of my configuration: OauthConfig: AuthConfig = { issuer: 'http://mydomain.identityserver4', ...

Unable to display complete content of Ionic 3 webpage

Trying to print a specific part of an Ionic page which contains a long list of items. However, encountering an issue where the entire list doesn't fit on one page and requires scrolling down to view all items. Expecting the print dialog, triggered by ...