What steps can be taken to verify that observables from distinct components have been fully executed?

I am faced with a situation where multiple components on a page are utilizing observables to fetch API data. I have implemented a loading service that is responsible for displaying a loader from the time the first observable is initiated until the last one is completed.

Here is an example of the loading service:

    private _loading = new BehaviorSubject<boolean>(false);
    readonly loading$ = this._loading.asObservable();

    showUntilLoadingComplete<T>(observable$: Observable<T>): Observable<T> {
      return of(null).pipe(
        tap(_ => this._loading.next(true)),
        concatMap(_ => observable$),
        finalize(() => this._loading.next(false))
      );
    }

The components utilize the loading service in the following manner:

    this.loadingService.showUntilLoadingComplete(someObservable$)
        .subscribe(data=> {
           // perform actions
        });

One issue that arises is that when the first observable completes, the behavior subject switches to false, causing the loader to stop showing. One potential solution I have considered is creating another behavior subject to store an array of active observables, removing them once they are finalized, and then monitoring the length of the array to determine when to turn off the loader. However, this approach does not seem optimal, so I am seeking suggestions from others.

Answer №1

If you're relying on the same loading$ Observable within a shared service, consider incorporating an additional property to track the current number of active calls and only deactivate the loading state when no other calls are active.

You could implement something similar to the following approach:

private _activeCalls: number = 0;
private _loadingStatus = new BehaviorSubject<boolean>(false);
readonly loading$ = this._loadingStatus.asObservable();

showUntilLoadingComplete<T>(observable$: Observable<T>): Observable<T> {
  return of(null).pipe(
    tap(() => {
      this._loadingStatus.next(true);
      this._activeCalls++;
    }),
    concatMap((_) => observable$),
    finalize(() => {
      this._activeCalls--;
      if (!this._activeCalls) {
        this._loadingStatus.next(false);
      }
    })
  );
}

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

Mistakenly importing the incorrect version of Angular

While working on my Angular 1 app in typescript, I faced an issue when importing angular using the following syntax: import * as angular from 'angular'; Instead of importing angular from angular, it was being imported from angular-mocks. Thi ...

All hail the powerful nodejs server.listen() function, the gate

My journey into learning about nodejs servers and websockets has just begun. Currently, I am exploring a server written in javascript using socket.io and express. var app = require('express')(), server = require('http').Server(app) ...

Can a self-referential type truly exist?

There is a function that takes in a configuration object containing color definitions. For example: useColors({ colors: { RED: { hex: 0xff0000 }, GREEN: { hex: 0x00ff00 }, BLUE: { hex: 0x0000ff } }, doSomethingWithColor(getColor) { g ...

Incorporate the AngularJS controller into your JavaScript code

I am facing an issue with my jQuery UI dialog that contains a dynamic <select> populated with Angular and AJAX. The problem is that the AngularJS script still runs even when the dialog is not visible. To solve this, I added a condition to stop the s ...

Utilizing Multiple Checkboxes for Precision Search Refinement

Big thanks to Khalid Ali for the support provided up until now. I am currently working with an array of songs that each have descriptions, keywords, etc. I have a set of checkboxes that I want to use to refine a search. Essentially, if someone selects the ...

What is the significance of the colon before the params list in Typescript?

Consider the following code snippet: import React, { FC } from "react"; type GreetingProps = { name: string; } const Greeting:FC<GreetingProps> = ({ name }) => { // name is string! return <h1>Hello {name}</h1> }; Wha ...

"Exploring the possibilities of the Raphael JavaScript Library on an iPhone

I've been trying to integrate the Raphael JavaScript library into my iPhone project, but I'm running into an issue with getting it to work in a webview. On Safari for Mac, everything seems fine and I can see the red circle as expected. However, w ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

How can one restrict the display of fields in the Meteor aldeed tabular package?

How can I restrict certain data from being displayed in an aldeed tabular datatable? For instance, if my collection includes attributes A, B, C, D and attribute C contains sensitive information that should not be published, is there a way to prevent it fro ...

Ways to funnel Firebase API endpoint towards an outside web address

When hosting on Firebase, how can I redirect all API requests from https://<domain>.web.app/api/v1/db/search?query=<something> To: http://<domain>:<port>/v1/db/search?query=<something> I've searched extensively online a ...

MongoDB and Node.js encounter unexpected outcomes due to undefined variables

I am trying to retrieve data from my collection called students within the pool database in MongoDB. Despite having a successful connection to the database, when I use console.log(result.lastname), it returns undefined. Below is an excerpt from my server ...

"Troubleshooting a malfunctioning PHP contact form that is not functioning properly

Here's some of my JavaScript code: var form = $('#main-contact-form'); form.submit(function(event){ event.preventDefault(); var form_status = $('<div class="form_status"></div>'); $.ajax({ url: $(th ...

Tips for showcasing personalized validation alerts with jQuery in the HTML5 format?

One of the Javascript functions I designed is for validating file extensions before uploading: function validateFileExtension(field, extensions){ file_extension = field.val().split('.').pop().toLowerCase(); if ($.inArray(file_extension,exten ...

The error message "TypeError: router.back is not a function" indicates that

Testing out the back route navigation in next.js and encountering an error during the test: https://i.sstatic.net/O6Nax.png The function for going back: const router = useRouter(); const handleClick = useCallback(() => { if (router ...

interactive form fields updating using javascript

Hey there! I'm a beginner in web development and currently facing a challenge. I have a form with 2 fields generated by one drop-down menu. I've managed to generate one field, but struggling to get the other due to my limited knowledge. I just ne ...

Dynamic font sizing in CSS allows text on a webpage to

I am working on creating a dynamic screen using AngularJS. Within this screen, there are objects with a specific size: .item { margin: auto; margin-bottom: 10px; width: 11vw; height: 11vw; text-overflow: ellipsis; overflow: hidden; } These i ...

PHP allows for creating dropdown lists where the values are dynamically dependent on the selection of another dropdown list within the same form

Is there a way for me to implement this solution? The values in the dropdownlist are based on another dropdownlist within the same form. For example, a form with dropdownlists for car names and models of that car, along with a search button. Please take no ...

Troubleshooting the issue of CSS animations activating twice and causing a flickering effect specifically in the Firefox browser

I am facing an issue with CSS animations in Firefox. When I try to slide in some radio buttons upon clicking a button, the animation seems to be firing twice in Firefox while it works fine in Chrome. I have attempted several solutions but haven't been ...

React Table component displaying data fetched from API is encountering errors when trying to access properties of null

While using React-Material-Table, I encountered an issue where some values are null, resulting in the error message "Uncaught TypeError: Cannot read properties of null (reading 'name')". 1. How can I address this problem? 2. Is there a way to se ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...