Search code examples
angulartimerrxjsobservablesubscription

Angular Countdown with rxjsTimer / observable subscribe


With Angular5.

I'm working on a livechat.

User can chat til the countdown reach 0.

On first user's input, the countDown start:

private engage_session() {

if(!this.is_engaged){

  this.countDown = Observable.timer(0, 1000)
    .take(this.counter)
    .map( () => --this.counter );   

  this.countDown.subscribe( remaining_credit => { this.remaining_credit = remaining_credit } );  
}

this.is_engaged = true;

}

I need to subscribe to the countDown so that i can use it in another func :

public sendMessage(message: Message): void
  {
    this.engage_session();

    if (!message) { return; }

    this.socketService.send({
      from: this.tokenUser.username,
      content: message,
      created_at: moment().format(),
      remaining_credit: this.remaining_credit || this.counter,
    });
    this.messageContent = null;
  }

I also have somthing like this in template:

 CountDown : <span class="badge badge-light">{{countDown | async | formatTime }}</span>

Problem is: when i subscribe to countDown, the timer goes twice as fast as it should be.

But when I remove the line:

this.countDown.subscribe( remaining_credit => { this.remaining_credit = remaining_credit } );

then the countdown is working fine..

Thanks for your help =)


Solution

  • It goes twice as fast, most likely, because you subscribe it twice (async is your second subscription). I am not fully aware of your structures and implementation, but I think you could simply do:

    CountDown : <span class="badge badge-light">{{remaining_credit | formatTime }}</span>

    If this HTML is from component which createscountDown observable