Using rxjs takeUntil will prevent the execution of finalize

I am implementing a countdown functionality with the following code:

userClick=new Subject()

resetCountdown(){this.userClick.next()}

setCountDown() {
    let counter = 5;
    let tick = 1000;
    this.countDown = timer(0, tick)
    .pipe(
      take(counter),
      map(() => --counter),
      takeUntil(this.userClick),
      finalize(() => {
        if (this.currentQuestionNumber < this.questionsToAsk)
          this.showNextQuestion();
        else {
          this.endQuiz();
        }

      })
    );
}

Now, I have a requirement that when takeUntil(this.userClick) interrupts the countdown, I do not want finalize to be executed. Is there any way to achieve this? The desired behavior is for finalize to only execute when the countdown reaches 0 without being interrupted by takeUntil.

Answer №1

If you want to check when a value reaches your target and perform certain actions, consider using the tap method.
Here is an example:

function setCountDown() {
    let counter = 5;
    let tick = 1000;
    this.countDown = timer(0, tick)
      .pipe(
        take(counter + 1),
        map(value => counter - value),
        tap(value => {
          if (value === 0) {
            console.log('OUT OF TIME');
          }
        }),
        takeUntil(userClick)
      )
}

You can view a demo of this in action in this example

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

How can I easily move from a shared page to a specific page in Angular 8?

Just stepping into the world of front-end development, I have a scenario where my menu page offers 3 options to navigate: Go to Arena. Go to Dungeon. Go to Battleground. However, clicking on any of these options leads me to a common page for character p ...

What are the best ways to utilize @types/bootbox and @types/jquery?

Is there a way to incorporate @types/bootbox and @types/jquery into an Angular 4 project? I attempted the following: npm install @types/bootbox and in my code, I am implementing it like so: import * as bootbox from 'bootbox'. However, I encou ...

Defined a data type using Typescript, however, the underlying Javascript code is operating with an incorrect data type

Recently delving into Typescript and following along with an educational video. Encountered a strange behavior that seems like a bug. For instance: const json = '{"x": 10, "y":10}'; const coordinates: { x: number; y: number } = JSON.parse(json); ...

Angular: Generating a fresh instance of an object monthly

My goal is to create an object called "Activity" in Angular 8, which will automatically generate an activity for each month upon creation. For example: export class Activity { activityID = string; activityName = string; startDate = Date ...

Efficiently integrating Firebase Functions with external sub path imports beyond the project's

I encountered an issue in my firebase functions project with typescript. The problem arises when I use types from outside the project with sub path imports, causing the build files to become distorted. Instead of having main:lib/index.js, I have main:lib/ ...

What is the best way to refresh existing data retrieved by React Query without having to fetch everything again?

My current code structure requires me to refetch all the data after a successful mutation, as the client-side tasks are not updated automatically. Is there a way to update the tasks directly when I create or delete a task? const { data: sessionData } = ...

Three.js - spinning texture applied to spherical shape

Would it be possible to rotate a loaded texture on a sphere geometry in Three.js without rotating the object itself? I am seeking a way to rotate just the texture applied to the material. Imagine starting with a sphere like this: https://i.sstatic.net/Ol3y ...

Having trouble triggering a change event within a React component?

I'm working on a straightforward react-component that consists of a form. Within this form, the user can search for other users. To ensure the form is valid, there needs to be between 3 and 6 users added. To achieve this, I've included a hidden ...

The ajv-based middy validator does not adhere to the specified date and time format

When it comes to validation, I rely on middy as my go-to package, which is powered by ajv. Below is an example of how I set up the JSON schema: serviceDate: { type: 'string', format: 'date-time' }, The structure o ...

Angular HTTP client failing to convert response data to specified type

Recently, I started using the new HttpClient and encountered an issue where the response is not cast with the provided type when making a call. I attempted to use both an interface and a class for casting, but it seems that only interfaces work as shown in ...

Submit user-specific form data in Angular 5 based on user selection

Utilizing a common reactive form to handle various types of user data, such as teachers, students, guards, etc. The form is selected from a dropdown list. The goal is to send specific data objects based on the selected user type. A model named "User" has ...

The functionality of translations within a TypeScript object is currently malfunctioning

I am facing a perplexing issue with my code. I am utilizing lingui for internationalization in my application. The translations are stored using the `t` macro in a TypeScript object, which can be found here: https://github.com/Flaburgan/disco2very/blob/mas ...

Deciphering TS2345: "The argument supplied, known as 'typeof MyComponent', cannot be assigned to the specified parameter type"

I am facing an issue while attempting to integrate a Typescript React component with react-onclickoutside. The error message that I encounter is as follows: TS2345: Argument of type 'typeof MyComponent' is not assignable to parameter of type &apo ...

Utilizing ngFor to generate buttons that are disabled based on specific conditions

I need assistance with creating a dynamic list of buttons from an array using ngFor. While I have achieved this, my current issue lies in disabling the buttons once they exceed a certain "number" representing the user's level. Here is an example of w ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

Strange behavior exhibited by the HTML DataList component within an Angular application

I have created a simple component that displays a list of data and allows users to add new entries. <h6 *ngIf="withHeader"><label for="select"> {{title}} </label></h6> <label *ngIf="!withHeader" [ngClass]="{'required&apos ...

When using Angular9 with PrimeNG fullcalendar, it may encounter issues such as errors stating "Cannot find namespace 'FullCalendarVDom'." and "Please import the top-level fullcalendar lib"

Using primeng p-fullcalendar in my angular application. Encountering an error in the command-line: 'Cannot find namespace 'FullCalendarVDom' Also seeing this error in the browser: 'Please import the top-level fullcalendar lib before a ...

What are the steps to enable readonly or disabled functionality in Ionic 2?

Trying to make a field readonly or disabled in an ionic2 form: <ion-item> <ion-label fixed>Category <ion-icon name="ios-arrow-forward"></ion-icon></ion-label> <ion-input type="text" [disabled]="false" id="category_ ...

A Guide to Handling Errors while Converting a Map to a Promise in Typescript

I am attempting to capture errors if any of the asynchronous code within my map function fails. It seems to enter the error block but does not log anything, as the error variable remains null. Is there an alternative method for handling errors within map ...

Why doesn't Typescript 5.0.3 throw an error for incompatible generic parameters in these types?

------------- Prompt and background (Not crucial for understanding the question)---------------- In my TypeScript application, I work with objects that have references to other objects. These references can be either filled or empty, as illustrated below: ...