Sign up for an observable only when a specific variable has been modified

I am facing an issue where I need to restrict the usage of rxjs's subscribe method to only certain property changes. I attempted to achieve this using distinctUntilChanged, but it seems like there is something missing in my implementation.

The specific requirement is for the subscribe function to be triggered only when the data.members[] property undergoes a change.

this.myService.loadData(this.data.id)
  .distinctUntilChanged()
  .subscribe(data => {
    this.data = data;
    console.log("data changed", data);
});

I would appreciate guidance on how to effectively respond to distinct changes in this scenario.

Answer №1

After reviewing the Rxjs v4 documentation, it appears that you can accomplish your goal using

Rx.Observable.prototype.distinctUntilChanged([keySelector], [comparer])
. This allows you to select a specific property to monitor for changes and use a comparer parameter to check for equality.

In Rxjs v5, there are both distinctUntilKeyChanged and distinctUntilChanged operators with similar functionalities.

If you need further guidance on implementation, you can refer to example usage in the tests: [distinctUntilChanged-spec.ts, distinctUntilKeyChanged-spec.ts]

If you encounter any difficulties while setting this up, feel free to share what you've attempted so far.

Answer №2

.distinctUntilChanged((data) => { return data.members; })
is effective! How can I detect changes in multiple arrays like members, relations, and children?

I am interested in responding to array modifications (additions/deletions).

To perform a deep comparison, utilize angular.equals.

this.myService.loadData(this.data.id)
  .distinctUntilChanged((data) => (data.members), (a,b) => (angular.equals(a,b))
  .subscribe(data => {
    this.data = data;
    console.log("data changed", data);
});

For further insights on distinctUntilChanged, refer to the RxJS distinctUntilChanged API Reference.

If you wish to learn more about angular.equals, check out the AngularJS angular.equals API Reference.

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

Executing a Javascript function within a PHP script

I am trying to retrieve JSON data from a JavaScript function and use it as a variable in PHP. Here is the function I have: <script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script> <script> $(fu ...

The function addClass() seems to be malfunctioning

I'm currently experimenting with creating a scrolling cursor effect on a string of text. The goal is to make it look like the text has been highlighted with a blinking cursor, similar to what you see in your browser's search bar. window.setInter ...

Sending data from local storage to ajax call

Below is the code snippet in question: $.ajax({ url: localStorage.getItem("isntagram link"), // url: "https://api.instagram.com/v1/users/self/feed?access_token=233291163.8a612cd.c49f77de073746e9a2f53116b720302e", met ...

The PHP script is not being activated by AJAX

I am completely baffled by the situation at hand. Sometimes, I open a different browser to test my changes and it works as expected. But then, when I try again, it fails. It's driving me crazy. On syllableapp.com, I set up a MySQL database that I can ...

retrieve information from a div using an AJAX request

I don't have much experience with ajax and javascript, but I need some assistance, so I will do my best to explain clearly! Below is the JavaScript associated with a button: $('#button-confirm').on('click', function() { $.ajax({ ...

Does the current protected route that I am on restrict the user from navigating back to the Home component?

I'm having trouble figuring out how to redirect the user to the Home component when they logout. The API is functioning correctly based on my tests. However, I am unsure of how to implement the logout method in the current context to successfully log ...

Retrieve the JSON element from a Backbone model by its unique identifier

I'm diving into Backbone for the first time and I'm facing difficulties making it work smoothly with a JSON data file. Here's how my model looks: window.Test = Backbone.Model.extend({ defaults: { id: null, name: null, }, url: f ...

Using AngularJS to send a $http.post request with Paypal integration

This form utilizes the standard PayPal format for making purchases. <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="<a href= ...

Ways to style a div element in CSS to achieve a unique shape

Hello there! I'm looking to achieve a tilted background div effect. Anyone have any tips or ideas on how I can do this? I'm new to web development and would appreciate the guidance. https://i.stack.imgur.com/wyj1X.png ...

Is Javascript Functioning Properly?

Similar Question: How do I determine if JavaScript is turned off? Can we identify whether javascript has been disabled and then redirect to a different page? I am currently working on a project using JSPs, where I have integrated various advanced java ...

Create a line break in an alert using PHP

<?php function alert($msg) { echo "<script type='text/javascript'>alert('$msg');</script>"; } if(array_key_exists('btnRegisterAdmins', $_POST)) { $fname = $_POST['FirstName']; $lname=$_POST['La ...

Comparing the distinction between assigning values to res and res.locals in a Node.js application using Express

Greetings! I am inquiring about the utilization of res (Express response object) and res.locals in Express. During my exploration of nodejs, I came across a code snippet that consists of a middleware (messages.js), a server (app.js), and a template (messa ...

Enable Row Editing with a Click in Material Table

Utilizing the material-table library, I am implementing a feature to enable table rows to be editable upon double-click. The goal is for clicking on a row to trigger the same action as clicking the edit button located in the actions column on the leftmost ...

Guide to inputting text into the Dev element

I am encountering a challenge with automating gist creation on GitHub. The issue arises when trying to input text into the gist content-box (see attached image). Despite attempting to use Javascript executer, I have not been successful. JavascriptExecutor ...

Changing a string to uppercase and lowercase

I am currently working on a software that takes a string, divides it, capitalizes the first letter of the first string, and capitalizes all letters in the second string. Below is the code snippet: var fullName = "ThEoDORe RoOseVElT"; function nameEditor( ...

Problem with the "md-open-on-focus" behavior in the Angular-Material's "md-datepicker" directive

When testing the functionality of the fiddle, an inconsistency issue was observed with multiple openings of the md-datepicker while using md-open-on-focus. The problem arises after the first successful opening and closing - subsequent attempts to open it ...

The scrolling feature within individual div elements seems to be malfunctioning in Ionic 2

In my current project using Ionic 2, I am faced with the task of designing a screen that contains two distinct grid views. The first grid view needs to occupy 40% of the height, allowing for scrolling within that specified area. On the other hand, the se ...

Convert a string with the characters '"' retrieved from a MySQL database into JSON

After creating a JSON object and storing it in MySQL, I encountered an issue when trying to retrieve and parse it. When I stringify the JSON object, the properties are being enclosed in double quotes causing issues when parsing the retrieved string. Below ...

Please ensure to log out when the user exits the tab

I am looking for a way to automatically log out users from my Django site when they close the browser tab or window. Ideally, I want users to be forced to re-enter their username and password if they try to access the site again after closing it without cl ...

The data from the method in the Vue.js component is not displaying as expected

Currently diving into Vue.JS (2) and exploring the world of components. My current challenge involves using a component within another component, grabbing data from a data method. Here's what I have so far: HTML <div id="root"> <h1> ...