RXJS - distinguishing between values based on multiple keys

I am looking to trigger .subscribe() for my observable when any one of three object keys has been changed.

The method works if I manually duplicate it for each key:

this.myService.loadData(this.dataContainer.id, true)
      .distinctUntilChanged((updatedData) => { return updatedData.relations; })
      .subscribe(updatedData => {
        console.log("relations changed",updatedData);
    });

this.myService.loadData(this.dataContainer.id, true)
      .distinctUntilChanged((updatedData) => { return updatedData.parent; })
      .subscribe(updatedData => {
        console.log("parent changed",updatedData);
    });

this.myService.loadData(this.dataContainer.id, true)
      .distinctUntilChanged((updatedData) => { return updatedData.children; })
      .subscribe(updatedData => {
        console.log("children changed",updatedData);
    });

If I modify the distinctUntilChanged comparer to return the entire updatedData object, the subscribe function never triggers.

Is there a way to combine the three dinstinctUntilChanged functions into one reducer?

Answer №1

The solution I came up with was implementing the following code:

.distinctUntilChanged((x, y) => x.id === y.id && x.name === y.name);

Answer №2

Here is one method:

const info$ = this.myService.fetchInfo(this.infoContainer.id, true);

Observable
  .combineLatest(
    $info.distinctUntilChanged(info => updatedInfo.relations),
    $info.distinctUntilChanged(info => updatedInfo.parent),
    $info.distinctUntilChanged(info => updatedInfo.children),
    info => info
  )
  .subscribe(updatedInfo => {
    console.log("relation|parent|children changed", updatedInfo);
  });

Answer №3

One approach could involve retrieving all the data within the selector and then using the comparison function to check for differences in various properties:

this.myService.fetchData(this.dataContainer.id, true)
  .distinctUntilChanged((newData) => { return newData; }, (x, y) => {
    return x.relations === y.relations && x.parent === y.parent && x.children === y.children;
  })
  .subscribe(newData => {
    console.log("newData", newData);
});

Answer №4

Here is a different method using lodash's pick and isEqual:

  updatedDashboardMessages$ = this.currentUser$.pipe(
    map((currentUser: User) => pick(currentUser, 'subscriptionStatus', 'payoutsEnabled')),
    distinctUntilChanged(isEqual),
    map((currentUser: Pick<User, 'subscriptionStatus' | 'payoutsEnabled'>) => {
      // This code snippet deals with partial user model data
    }),

  );

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

Ways to revert all modifications to styles implemented using JavaScript

Hey there, just checking in to see how you're doing. I was wondering if there's a way to reset all the styles that have been changed using JavaScript? I'm referring to the styles shown in this photo: https://i.sstatic.net/Zawjt.png Thanks ...

Tips for obtaining a refresh token

Struggling to connect with the Google Play Android API despite following numerous instructions. Stuck at step 4 of the authorization process (Authorization documentation) where it requires sending a POST request with specific parameters: The code snippet ...

Is it possible to utilize the "let" keyword in JavaScript as a way to prevent global-scope variables?

While working on a JavaScript test, I came across an interesting observation related to the let keyword. Take a look at this code snippet: let variable = "I am a variable"; console.log(window.variable); Surprisingly, when I tried to access the variable p ...

Significant issue identified with ajax functionality, requiring immediate attention

After executing the code in the console, I expected to see the ajax object with a readyState of 0 (as I aborted the ajax call). However, Chrome is displaying the number 4 in the console instead of 0. This discrepancy is surprising. http://jsfiddle.net/8yC ...

A guide on accessing URL query parameters using AngularJS

Is it possible to extract specific URL parameters using AngularJS and then assign their values to textboxes? For instance, a sample URL would be: http://example.com/?param1=value1 I've come across examples involving $location, routing, and services ...

Is AngularJS Authentication Service Capable of Supporting Promises?

I have recently set up an authentication service that I inject into my Login controller. When I use it to perform a login, the process involves calling the service like this: $scope.login = function() { var loginResult = authentication.login($scope.m ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Delete a div when a button is clicked through JavaScript

I'm having an issue with a form I created that duplicates itself - I can't seem to get the 'x' button to remove the corresponding div as needed. I have placed both buttons outside of the div like this: <button type="button" id="cro ...

JavaScript Callbacks and Promises: Exploring Asynchronous Programming

For the past 2 days, I've been struggling to figure out my mistake. It seems that I can't get past the "undefined" returned value because I'm having trouble grasping callbacks or promises. Despite reading numerous posts and trying simple exa ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

rearrange elements in the HTML code

I need to display 3 tables, each with a width of 300px, on a webpage. These tables can be collapsed or visible. My goal is to arrange them so that if only one table is visible, it appears in the center of the page (centrally aligned). Additionally, the tab ...

The Homescreen.js file is not showing up as expected on the localhost/home page and is not displaying

Struggling to showcase the rooms on my hotel reservation website. Can't seem to crack it. Need some assistance, please. Spent a good 3 hours trying to figure this out. Snippet from My Homescreen.js import React ,{useState, useEffect, } from &apo ...

Key Assignment in Vue FireStore - Potential Undefined Object Situation

My goal is to assign Firestore data, passed through props, to a reactive proxy object in Vue. However, I am encountering an error that says: Object is possibly 'undefined'. (property) fireStoreData: Record<string, any> | undefined To strea ...

What are the implications of an unidentified callback function with parameters?

Check out this snippet: const fs = require('fs'); fs.readFile('foo.txt', 'utf8', (error, data) => { if (error) { throw new Error(error); } console.log(data); }); Can you figure out where the anonymous callback is recei ...

Choose and target any element on the page using jQuery

Can someone help with selecting any element on a webpage, such as clicking on the body, a div, or a specific ID, so that I can save it to a variable for later editing? I've attempted: $("*", document.body).click(function (e) { e.stopPropagation() ...

Asynchronous data fetching with React Hook useEffect does not properly populate the tooltip in Material UI component

After using useEffect to fetch data, I encountered a problem in passing the data to my component. Here is some of my code: User Data Types (UPDATED) export interface IUser { display_name: string; id: string; images: Image[]; } expo ...

Using the Karma testing framework to interact with the service of an AngularJS application

Currently, I am in the process of creating an end-to-end test using Karma for an AngularJS application. My goal is to automate the process of filling out a form and submitting it. Once submitted, an object is generated that should be accessible by calling ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

The Yeoman gulp-angular setup encountered an Eacces error due to permission being denied

After attempting to install the application with yo gulp-angular my-first-app, an error occurred: Error : return binding.open(pathModule._makeLog(path),stringtoFlag(flags),mode); Eacces permission denied. An image of the full error stack from the termina ...

The jQuery plugin functions smoothly when running on localhost, but it causes issues with the background image when deployed on the web

I created a compact plugin to show a cookie message. While testing it on my local machine, everything functioned smoothly without affecting any web pages. However, once I transferred the files to the server, I encountered issues such as: A background ima ...