Angular - postpone function execution until Subject has completed its operation

In my code, there is a function that stops a running process using a specified processId. Before this function is executed, there is a single if statement that checks if a valid processId exists, and if so, it calls the cancel() function.

if (this.processId) {
  //...
  this.processEngine.cancel(this.processId, this.entityUid).subscribe(
    ...
  );
} else {
  console.log('No active process to cancel');
}

When initiating the process, a loading screen with a loading animation and a Cancel button is displayed. However, there is a small issue where, under certain conditions (such as throttling via developer tools), the user can click the Cancel button before the processId is initialized, resulting in the process not being cancelled.

There is a Subject in the service that holds the processId value once the process starts successfully and is immediately completed thereafter.

private startSubject = new Subject<string | null>();
...
// inside start function
this.startSubject.next(processId);
this.startSubject.complete();

Additionally, there is a BehaviorSubject that is set to true when the project is started and running.

active: BehaviorSubject<boolean> = new BehaviorSubject(false);

I attempted to modify the existing if statement to include this.active.value, but I am struggling to delay the cancel call until the startSubject is completed. I tried using debounce, but it did not work as expected as the cancel method was called with undefined, resulting in an error.

this.processEngine.cancel(this.processId, this.entityUid).pipe(
  debounce(() => 
    return this.startSubject.asObservable()
  )
)
.subscribe(...);

Answer №1

If I have correctly understood your requirements, it seems that you want to achieve the following -

Before any action is taken upon clicking the "Cancel" button, the value of "processId" must not be null.

If my interpretation is accurate, you can implement the following solution -

// Setting up a Behavior subject to keep track of processId
processId$: BehaviorSubject<any> = new BehaviorSubject<any>(null);

// Creating an observable for the cancel button click event
this.cancelClick$ = fromEvent(this.button.nativeElement, 'click');

// Creating an observable that emits only when processId is not null
const notNullProcessId$ = this.processId$.pipe(filter(processId => !!processId));

// Combining both observables to achieve the desired functionality
notNullProcessId$.pipe(
                  switchMap((processId) => {
                    return this.cancelClick$
                               .pipe(
                                 switchMap(() => {
                                   return this.processEngine.cancel(processId, this.entityUid);
                                 })
                               );
                  })                      
                ).subscribe(cancelResult => {
                  // Perform actions based on cancel result
                  console.log(cancelResult);
                });

// This function is triggered by the consumer to set the processId
emitValue(processId) {
    this.processId$.next(processId);
    this.processId$.complete();
  }

Please confirm if this solution fits your requirements.

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

Extracting live TV channels from an m3u file by differentiating them from VOD content

Currently, I am developing an IPTV player app and have successfully parsed the m3u file. My current challenge is separating live TV channels from Video on Demand (VOD). I am unsure of where exactly the transition happens in the playlists. Below are the ke ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

Tips for refreshing tab body data in Angular Material when switching between tabs

Check out this example code snippet Main Controller <mat-tab-group id="report"> <mat-tab label="Quiz"> <div class="demo-tab-content"> <app-quiz></app-quiz> </div> </mat-tab> <mat-tab label="Exam"> <di ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

Potential Null Object in Typescript Mongoose: A Concern

Encountering an issue while attempting to locate my user model: Object is possibly 'null'. I would like to find a solution that does not involve suppressing TypeScript's strict rule. const { email, password } = req.body; const user = awai ...

Translation of menu item label has not been executed

Here we have a component called SidebarMenuComponent that is not translating the labels of its menu items correctly. The goal is to get the labels translated, but the current implementation is failing. What is the correct approach to apply translation in t ...

Using TypeScript to create a state object in Koa

I am currently utilizing Koa () as the framework for my backend, which consists of Node.js + TypeScript. Koa permits and recommends using the built-in `ctx.state` to store and pass data between different middleware functions. I have been adhering to this ...

A guide to effectively utilizing a TypeScript cast in JSX/TSX components

When trying to cast TypeScript in a .tsx file, the compiler automatically interprets it as JSX. For example: (<HtmlInputElement> event.target).value You will receive an error message stating that: JSX element type 'HtmlInputElement' is ...

What could be causing the issue of my application not being able to operate on the specified port on Heroku?

After spending two whole days trying to decipher the Heroku error message with no success, I'm still unable to pinpoint what is causing the issue. 2021-07-18T04:27:08.741998+00:00 app[web.1]: {"level":30,"time":1626582428741,&quo ...

Trouble accessing nested components in Angular CLI beyond the first level of components

I'm diving into Angular CLI for the first time and trying to recreate a previous web project of mine. I've managed to nest and display components inside the root component successfully, but after that, I'm facing issues referencing any compo ...

What is the method for changing the language of column names in a grid by simply clicking a button?

Greetings Everyone, I'm fairly new to angularjs and I'm seeking guidance on how to translate column names into another language on a grid by clicking a button. While I've managed to retrieve column names in English, I am unsure about how to ...

steps for making a specific cell editable in tabulatorI'm happy to help

click here for image description required initializeTabulatortableBng() { let thisClass = this; let bngTableData = thisClass.tableDataWorm; function formatDecimal(cell) { var value = cell.getValue(); if (value !== null && value !== undefine ...

Different component instance captures the EventEmitter from a component inside ng-template

After developing a component with an event, let's refer to it as (onAction). This component is utilized in two different places within the same parent component or page, both of which are individual components themselves. The only variation between th ...

Creating a constant.ts file to define universal constantsWould you like assistance with anything else

Is there a way to create a constant.ts file or use a command to declare all global constants and export them for easy access? ...

What is the best way to protect an Angular/Spring application using Keycloak?

I am seeking to enhance the security of my Spring Boot (backend) and Angular (frontend) application by implementing Keycloak for authentication. Currently, I have a simple deployment setup where the executable jar created by Spring serves both the backend ...

Encountering a 405 error when making an OpenAI API call with next.js, typescript, and tailwind CSS

I encountered a 405 error indicating that the method request is not allowed. I am attempting to trigger an API route call upon clicking a button, which then connects to the OpenAI API. Unsure of my mistake here, any guidance would be highly appreciated. E ...

What is the syntax for typing the router instance in Next.js?

I'm working on a password reset request form in my Next.js project. Here's the code I have: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } fro ...

There are no route parameters defined

Within my user template file, I have a tab control implemented as shown below: <nav md-tab-nav-bar> <a class="tab-label" md-tab-link [routerLink]="'following'" routerLinkActive #following="routerLinkActive" [acti ...

Hover Effect for 3D Images

I recently came across an interesting 3D Hover Image Effect that I wanted to implement - https://codepen.io/kw7oe/pen/mPeepv. After going through various tutorials and guides, I decided to try styling a component with Materials UI and apply CSS in a differ ...

error TS2339: The attribute 'properties' is not accessible on the class 'TestPage'

Utilizing a typescript abstract class as the base class of my layout component in React has been essential for my project. The implementation of this base class looks something like this: import { IPageLayoutActions, IPageLayoutLocalState, IPageLayoutProp ...