Patience is key when waiting for the completion of a subscription in Angular 8

In my component, I have set up a subscription inside an interval in the onInit method:

  ngOnInit() {    
    interval(5000).pipe(
      takeWhile(() => this.isAlive))
      .subscribe(() => {
        this.initialization();
      });    
   }

initialization() {
    this.subscriptions.add(
      this.someService.someMethod().subscribe(
        data => {
          this.myData = Object.assign({}, data);
          this.var1 = this.myData.x; // Binding var1 to a text element in HTML
          this.var2 = this.myData.y; // Binding var2 to a text element in HTML
        }
      )
    );
  }

var1Change(value) {
    // Check if my code is in observable, once it completes, execute save immediately. How can I achieve this?
    this.var1 = value;
    this.myData.x = value;
    this.callSave();
}

callSave() {
    // Method to consume API and save data to file
}

Every 5 seconds, the UI updates with any changes in the data.
I can edit the data from the UI and automatically save it by consuming the API - the save action only triggers when there's a change in the model without the need for a save button.
What I want is to wait for the save process to complete if my code is within the observable.
Please assist me with the current code structure, as I am required to use interval and Save call in this manner.

Using angular 8.2 and rxjs 6.4

Answer №1

To delay saving data while an update is in progress, you can implement the following approach.

updateSubject = new Subject<any>(); //subject for update completion notification
saveSubject = new Subject<any>();  //subject for saving data
updateInProgress = false; //flag to track update status

constructor() {
  this.updateSubject.subscribe(() => this.updateInProgress = false); 
}

 ngOnInit() {    
    interval(5000).pipe(
      takeWhile(() => this.isAlive))
     .pipe(tap(()=> this.updateInProgress = true)) //mark update as in progress
     .subscribe(() => {
        this.initializeUpdate();
     });    
}
initializeUpdate() {
this.subscriptions.add(
  this.someService.performUpdate().subscribe(
    data => {
      this.updatedData = Object.assign({}, data);
      this.value1 = this.updatedData.a; // Bind value1 to HTML text element
      this.value2 = this.updatedData.b; // Bind value2 to HTML text element

      this.updateSubject.next(); //notify when update completes
    }
  )
);
}

value1Changed(newValue) {
   if(!this.updateInProgress) {
      this.saveData();
   } else {
    forkJoin(this.saveSubject.pipe(take(1)), this.updateSubject.pipe(take(1))).subscribe(() => {
      this.saveData();
  }
      this.saveSubject.next();
   }
}

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

Grafana: Simplifying time series data by eliminating time ranges or null values

Is there a way to remove the time on the axis of a realtime time series graph when there is no data between 11:30-13:00? The data source is clickhouse. enter image description here enter image description here I attempted to connect null values, but it wa ...

Creating Transparent Rounded Backgrounds in Google Chrome Packaged Apps: Achieving the same look as Google Hangout app

Looking at the screenshot below, it is evident that the Hangout app has a fully transparent design with background shadow effect applied to it. I have tried various methods in vain, such as applying CSS styling to the "html" and "body" tags of the page, a ...

Continuous Updates to innerHtml in Angular2

While working on a project, I encountered an issue that seems to be more about style than anything else. The endpoint I am calling is returning an SVG image instead of the expected jpeg or png format, and I need to display it on the page. To address this, ...

Arranging an upgrade within a task management app

I'm currently in the process of developing a task management app with AngularJS, Node, Express, and MongoDB. Everything seems to be falling into place except for the update functionality. I'm struggling with implementing this feature, especially ...

The process of locating a textarea by its id becomes obsolete when integrating CKEDITOR

The data table has editable cells, where clicking on a cell will trigger a bootstrap modal to display with a textarea containing the text retrieved from the database. Snippet of the table structure: <table class="table table-striped table-hover" id="t ...

Guide on combining two JSON Array objects in Nodejs

Is there a way to merge two JSON Array objects together using Node.js? I am looking to combine obj1 + obj2 in order to create a new JSON object: obj1 = [ { t: 1, d: 'AAA', v: 'yes' }, { t: 2, d: 'BBB', v: 'yes& ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

The AngularJS uib-typeahead feature seems to be disrupting the interpolation process for the entire page

Encountering an issue with AngularJS 1.50 where interpolation stops working after a specific line of code. <input type="text" class="form-control" id="search" name="search" placeholder="{{ shouldInterpolateButDoesnt }}" typeahead-on-sel ...

The assurance of quick delivery isn't effective

I am a beginner when it comes to working with promises and I'm struggling to implement them in my code successfully. Currently, I have a NodeJS server set up using the Express library along with express-promise. var express = require('express&a ...

The canvas could not be loaded properly in THREE.Texture()

I'm having trouble with adding an image onto the side of a cube that I'm creating. The image loads onto the canvas, but I'm struggling to incorporate it into the texture. function createPictureCanvas(text, font, foreground, background, xres ...

Is it possible to use JavaScript to retrieve a client's bookmarks with their consent?

Is there a way to streamline the process of importing bookmarks to my server for users? Can I use JavaScript to automatically retrieve a user's bookmarks, or is that not possible due to security concerns in browsers? ...

I'm having trouble getting my state to update in React when using useState

I am facing an issue with rendering a component that has a route using react router. The first component contains a button, and upon clicking it should render another component with state passed down from the initial component. However, even though the pag ...

Deactivate a Specific Popup for a Specific Page

In my project, I have a file called modal.php that contains two modal windows: Login Modal Feedback Modal The Login Modal automatically pops up every 5 seconds for users who are not logged in. The Feedback Modal opens when clicked. On my website, I hav ...

Encounter a problem with AngularJS 2 HTTP functionality using ES5 syntax

Trying to utilize http with Angular2 and encountering an issue. The code snippet is as follows: var _domain = 'http://localhost:3000/'; app.Applications = ng.core.Injectable().Class({ constructor: [ng.http.Http, function(http) { ...

"Responding to an Ajax request with a .NET Core server by sending an xlsx

My web application exclusively supports .xlsx files. I have implemented a function in my controller that converts .xls files to .xlsx format successfully. When trying to open a .xls file, I send it via an Ajax request. However, the converted .xlsx file do ...

Generating Multilayered PDF files with JavaScript in NodeJS

After reviewing the documentation for PDFMake, PDFKit, and WPS: PostScript for the Web, I couldn't find any information beyond background layers. It seems like Optional Content Groups might be what I need, but I'm unsure how to handle them using ...

Implement the Bootstrap datetimepicker functionality for the specified div element

The date picker successfully functions when I assign the id to the input tag as shown below: <div class="col-sm-4" id="datepicker"> <input type="text" class="form-control" id="inputDate" placeholder="Date"> <span class="glyphicon gl ...

What is the best way to make a JSONP request using jQuery?

Whenever I try to access this API through the browser, everything works fine and I receive the correct response. However, when I attempt to call the API using jQuery AJAX, I encounter an error. *The script is being refused execution from 'http://api ...

Incorporating Moment.js into React Native Typescript for Enhanced Date and

I am currently facing an issue while using Moment.js and React Native to work with date and time. My code snippet below showcases how I am attempting to utilize the library. import * as React from 'react'; import { Text, View, StyleSheet } from ...

Error: The function `map` is not available on the variable `filtredItems

Can anyone please help me out? I tried creating a simple code to filter items based on an input value, but I encountered an ERROR :( even though I am confident that I followed the tutorial steps correctly. You can find the tutorial here This is the compl ...