Using Rxjs to reset an observable with combineLatest

My scenario involves 4 different observables being combined using "combineLatest". I am looking for a way to reset the value of observable 2 if observables 1, 3, or 4 emit a value. Is this possible? Thank you!

  1. Mat-table sort change event (Sort class)
  2. Mat-table change page event (PageEvent class)
  3. Custom observable (filter)
  4. Custom observable (other filter)
combineLatest($1, $2, $3, $4).subscribe(([a, b, c, d]) => CALL_HTTP_WITH_PARAMETERS(a, b, c, d))

Example (initial values)

$1 = name,asc
$2 = 2
$3 = bla bla
$4 = bla bla

CALL_HTTP_WITH_PARAMETERS("name,asc", 2, "bla bla", "bla bla")

Observable 1 emits the value "name,desc"

$1 = name,desc
$2 = 2 ==> should be reset to 1
$3 = bla bla
$4 = bla bla

CALL_HTTP_WITH_PARAMETERS("name,desc", 1, "bla bla", "bla bla")

Other scenario

Observable 3 emits the value "new value"

$1 = name,asc
$2 = 2 ==> should be reset to 1
$3 = new value
$4 = bla bla

CALL_HTTP_WITH_PARAMETERS("name,asc", 1, "new value", "bla bla")

Answer №1

If you're looking for a strategy to reset variables in your code, here's a suggestion:

Let's say you have the following variables: $a, $b, $c, and $d, which are Observables. To reset $b when $a, $c, or $d changes, you can define them as Subjects and then pipe them to reset $b.


const $aSubject = new Subject()
const $bSubject = new Subject()
const $cSubject = new Subject()
const $dSubject = new Subject()
const $a = $aSubject.asObservable().pipe(
  tap(() => $bSubject.next(0))
)
const $b = $bSubject.asObservable()
const $c = $cSubject.asObservable().pipe(
  tap(() => $bSubject.next(0))
)
const $d = $dSubject.asObservable().pipe(
  tap(() => $bSubject.next(0))
)

However, this setup can lead to an infinite loop in the combineLatest() function. To prevent this, you can use the distinctUntilChanged operator on the Observables.

Another issue to address is unnecessary HTTP calls. By using the switchMap operator, you can ensure that only one call is made even if the parameters trigger multiple updates.


combineLatest([$1, $2, $3, $4]).pipe(
  switchMap(([a, b, c, d]) => callHttp(a, b, c, d))
)

For a demonstration of this concept, you can check out this simple demo.

Answer №2

There is no way to reset the observable once it's been set.

Consider reevaluating what the observable is tracking and make the necessary adjustments.

One approach could be:

merge($1, $3, $4).pipe(
   tap(_=> this.myGrid.setPage(1))
).subscribe()

If you have no control over the situation, you can create a Subject and utilize the next method.

Here's an example implementation:

subject2 = new Subject<number>();
$2 = this.subject2.asObservable();
onPageChanged(pageNumber:number){
   this.subject2.next(pageNumber);
}

merge($1, $3, $4).pipe(
   tap(_=> this.subject2.next(1))
).subscribe()

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

Unable to redirect with Asp response.redirect

I have a Login popup form where I use an ajax post request to Login.asp script in order to prevent the page from going to the POST URL after submission. <script> $(function() { $('#contactForm').submit(function(e){ e.preventDe ...

Tips for including the % symbol in the Y-axis labels on a HighChart graph

https://i.sstatic.net/Ym7Uz.png I am attempting to incorporate the % symbol after the value of 100 or -100 on the yAxis in the chart shown above. I made an attempt to add the % symbols as follows: quotes.data.frequency_counts[i].negative = Math.round(ne ...

Guide to transferring filtered data to the controller

As I work on designing a user interface for managing project applications, one of the key functionalities is the ability to filter applications by their type. Within the UI, there is a prominent button labeled select ALL which, when clicked, is meant to se ...

Tips for adding color to the <td> element in an ejs file using nodeJS

I am looking to incorporate a color into my .ejs file. Here is the code snippet I am working with: <% resultList.forEach(function(item, index){ %> <tr> <td><%= item.function %></td> <td><%= item.value %>< ...

Enable automatic profile login for the Firebase application

Imagine a web application created using Vue and Firebase. The main query revolves around automatically logging into the app after page reload, particularly accessing the database post authorization. Following user authentication, crucial data such as email ...

Displaying text that follows the cursor on a JavaScript mouseover event

When I hover over the pin with my cursor, the text should move along with the mouse. However, the current position of the text is off and needs to be adjusted to be next to the pin. What is a more accurate way to calculate the correct position? var toolt ...

Assistance for Angular 2 Style Guide within Atom: Feature Needed!

My manager uses Atom with a set of eight plugins specifically designed for Angular development. I have the same plugins installed on my system, but I seem to be missing a feature that he has. We're unsure which plugin or preference setting is required ...

How to retrieve text values across various browsers using Vue.js

Whenever I type something in a text box, it displays the text value based on its ID. This code works perfectly when running it on my laptop at http://localhost:8080/. If I open the same website on my phone at http://xxx.xxx.x.xxx:8080/, it shows the same ...

Updating an image using AJAX and Flask

I have a situation in HTML where I need to constantly update an image file with the latest images that come in. Below is the Flask code snippet: @app.route('/uploads/update_file', methods=['GET', 'POST']) def update_file(): ...

Submitting an ajax form with the use of the symbol '&'

I am currently working on a form submission using the .ajax() method. Within my script, I have the following code: data: dataString, The variable dataString is composed of: var list = $('.listsummary').val() The listsummary class is assoc ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Reinitializing the database with Cypress (postgresql)

When populating the database, I intentionally do it partially for certain tests. However, after completing all tests, I would like to reset the database in order to avoid any complications that may arise during the next populate process. How can I efficien ...

Sneaky spam and ads embedded within Joomla template

Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

Navigating a plethora of unpredictable identifiers using AngularJS

My goal is to display content from a json file that varies in type and consists of pages divided into chapters. Users can navigate through the content using an aside menu or next and previous buttons. Currently, I am able to display the content by inserti ...

Tips for preserving a string in angularJS or Java (and implementing it in an iframe)

My plan involves utilizing a Java web service to fetch the HTML content from a specific URL using Jsoup, and then returning it as a string to the requesting party, which could be an Angular or JS script. I am keen on preserving this content somewhere and l ...

What purpose does a private property serve within the interface?

Given the following code snippet: class X { bar() { return "bar" } constructor(private readonly x: number){} } interface Y extends X { } const f = (y: Y) => { console.log(y.bar()); } f({ bar: () => "tavern"}); The code does ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

What is preventing me from being able to effectively transmit the array using the POST method in Express?

As a newcomer trying to learn Express, I believe I am on the right path, but I am currently facing some challenges with the POST method. The issue I'm encountering is as follows: Whenever I send a POST request to an HTTP file, I receive an empty ob ...

Looking for guidance on sending data from a JS file to HTML using Nodejs? Seeking advice on various modules to achieve this task effectively? Let's

Looking for advice on the most effective method to transfer data from a JS file (retrieved from an sqlite db) to an HTML file in order to showcase it in a searchable table. My platform of choice is NodeJS. As a beginner, I am willing to put in extra time a ...