Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs takeUntil do not execute finalize

I have the following countdown:

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();
        }

      })
    );
}

When takeUntil(this.userClick) occurs, I do not want finalize to be executed. Is there any possibility to achieve that? I only want finalize to be executed when the countdown has reached 0 and was not interrupted before by takeUntil

like image 965
farahm Avatar asked Jan 27 '26 21:01

farahm


1 Answers

You can use tap to check if the value has reached your target and execute sideeffects.
Something like

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)
      )
}

See this example

like image 52
kos Avatar answered Jan 30 '26 12:01

kos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!