简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM