Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed.

// To start, install rxjs using npm
const Rx = require('rxjs/Rx');

let subject = new Rx.BehaviorSubject(null)
Rx.Observable.timer(0, 1000).subscribe(i => someApiCall(i));
// At this point, an xhr request will be sent every second

function someApiCall(i){
    // Fetch some data
    console.log("xhr request sent")
    subject.next(i);
}

// Now we subscribe to the subject, making prior xhr requests useless
let subscription;
setTimeout(() => subscription = subject.subscribe(i => console.log(i)),2500);
setTimeout(() => subscription.unsubscribe(),6000);
// Despite unsubscribing, the xhr requests still continue

I opted for the behaviorSubject instead of directly subscribing to the observable because I need to instantly receive the last value from the previous xhr request when resubscribing.

Answer №1

const { Observable } = Rx;

function makeApiRequest(i){
  return Observable.create(observer => {
    console.log("xhr request sent")
    observer.next(i);
    observer.complete();
  });
}

const dataStream = Rx.Observable.timer(0, 1000)
  // map each value to the values of makeApiRequest
  . mergeMap(i => makeApiRequest(i))
  // share the values through a replaySubject
  .publishReplay(1)
  // Only connect to the source when there is at least one subscriber
  .refCount();

dataStream
  .take(5)
  .subscribe(value => console.log(value));

dataStream
  .take(1)
  .subscribe(value => console.log(value));

It's important to note that using .take(1) for every subscription may not work as intended because each subscription will receive the value in the ReplaySubject and then unsubscribe before a new xhrRequest can be made.

In other words, something needs to keep the stream active long enough for the interval to continue triggering the requests.

Answer №2

It is recommended to utilize .ShareReplay(1) instead of relying on a BehaviourSubject. This method allows you to maintain laziness and cache the last value of your XMLHttpRequest.

const source = Rx.Observable.interval(1000)
  .mergeMap(I => doXhr())
  .shareReplay(1);

source.subscribe(console.log)

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 transfer all the formatting from the original file for the window.print() function. Localhost is functioning properly, but encountering issues with production

I'm encountering an issue with getting all styles from my Vue app. I have tried the code provided in this answer: https://stackoverflow.com/questions/52343006/how-to-print-a-part-of-a-vue-component-without-losing-the-style While it works fine on loc ...

What is the process for adjusting the form transition?

I am currently working on a form that has a transition effect However, I encountered an issue: check out the problem here My goal is to keep the magnifying glass fixed in place while the form moves Here is a snippet of my code: import Search fro ...

Using AngularJS to Dynamically Set the Default Selection in a SELECT Element

In my code using JADE syntax, I have the following structure: select(ng-model="eventTypeUI") option(ng-repeat="c in eventUI", ng-value='c.value', ng-disabled='selectEventCanNotBeUsed(c.value)') {{c.name}} ...

What sets apart the process of installing AngularJS and AngularJS Core using NuGet?

I am curious about the difference between these two packages in my packages.config file. Would it be advisable to uninstall one of them? <?xml version="1.0" encoding="utf-8"?> <packages> <package id="angularjs" version="1.3.15" targetFr ...

Sending data with React using POST request

Currently in my React application, I have a form that includes fields for username and password (with plans to add "confirm password" as well). When submitting the form, I need it to send JSON data containing the email and password in its body. The passwo ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...

Creating a REST API with the POST method using Vanilla JavaScript/AJAX and encountering a 400 error (Bad request) issue

Could you assist me in figuring out how to utilize the POST method in vanilla JavaScript (without jQuery)? I've been attempting to do so with this code: var call = { "filterParameters": { "id": 18855843, "isInStockOnly": false, "newsOn ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

Troubleshooting: Issues with Angular2 compatibility on Safari version 9.1.2

I am encountering an issue with running my angular2 app on Safari 9.1.2. It works fine on all higher versions of Safari as well as other browsers such as Chrome, Firefox, Opera, and Edge. However, when I try to run it on Safari 9.1.2, I receive the followi ...

Add the item to the array and then use the *ngFor directive to iterate

Whenever the addRoom button is clicked, I want to add an object to an array. The problem is that the data in my array keeps getting repeated. Please excuse any language errors in my explanation. Feel free to ask me for clarification in the comments below. ...

Angular: Utilizing Nested ng-repeat Alongside groupBy Feature on Initial Page Load or Refresh

With some help, I've made it this far on my project. However, I need to take one more step to achieve my goal. I want to group data based on an attribute that is currently passed through an ng-click action. Is there a way to automatically do this on p ...

Achieving Efficiency with Handlebars: Streamlining Remote Template Organization and

I am looking for a way to better organize my HB template by splitting it into different HTML files. In this case, I have created a file called helpers.html. This file contains two script tags: <script id='alert' type='text/template>... ...

Unresponsive display on both 'Ionic development application' and 'physical mobile device'

As a newbie to Ionic, I recently delved into the world of Ionic 4 by following the guidance provided in the Ionic 4 documentation. After setting up my project using ionic start myApp sidemenu --type=angular, I noticed that everything ran smoothly on my bro ...

The OrderBy Pipe in Angular 4 fails to sort correctly when the name of the item being sorted

How can I sort names ending with numbers using a custom pipe? I have successfully implemented a custom pipe for sorting and it is working as expected. $Apple fruit -symbol 1Apple fruit -numbers Apple fruit -alphabetically However, the custom pip ...

Checkbox malfunctioning when trying to add values after being checked

I have successfully completed a calculation system project using JavaScript. Everything works well, the calculations are accurate and taxes are included properly. However, I am facing an issue where the tax is not being included when I click on the checkbo ...

Unable to redirect to the initial page successfully

My React application is using Redux-Toolkit (RTK) Query for user login functionality. When the user clicks the "logout" button, it should redirect to the home page ("/"). However, I'm facing an issue where clicking the "logout" button does not trigger ...

Is it just me, or does the this.router.subscribe method no longer exist in Angular 2's @angular/router library?

I'm experiencing an issue in Angular 2 with the library @angular/router. It appears that the method this.router.subscribe no longer exists. Previously, this code worked fine on an older version of the router that has since been deprecated. Does anyon ...

Encountering: Unable to break down the property 'DynamicServerError' of 'serverHooks' as it does not have a defined value

An error has arisen in a Nextjs app with TypeScript, specifically in the line of my react component which can be found here. This is my inaugural package creation and after several trials, I managed to test it successfully in a similar vite and TypeScript ...

What is the optimal arrangement for constructors or classes in JavaScript code?

Constructors, being objects that are stored as copies, appear to behave similarly to variables in terms of their placement within the code. Unlike functions, constructors cannot be placed "anywhere" and must instead be positioned above the area where they ...

Is there a method to restrict the scope of identical components appearing multiple times on a single page in Angular 7?

I have a scenario where I need to place multiple instances of the same component on a page, but when one of them receives input and refreshes, all other components also refresh. Is there a way to prevent this from happening? <tr *ngFor="let map of imgs ...