[Fixed] Debounce Time when click on button Angular

Issue

I am new in RXJS and i want to implement debounce time when click on button.
This is my button:

 <button mat-mini-fab (click)="send()" [disabled]="!message.text || message.text.length === 0 || room.length === 0 || !room">
    <mat-icon>send</mat-icon>
  </button>

And this is my method for send:

public send(): void {
    this.message = { ...this.message, room: this.room, sender: this.currentUser, createdAt: new Date() };
    this.sendMessage.emit(this.message);
    this.clearMessage();
  }

How can i implement this, any suggestion?

Solution

You can achieve this with a litte trick.

// define a Subject
private rxjsSimulator: Subject<number> = new Subject();

// instantiate a Subscription in order to end the Subject-subscription when you leave the component
private subscription: Subscription = new Subscription();


// subscribe to the rxjs simulator
constructor() {
  this.subscription.add(
    // Here you can set your debounce time
    this.rxjsSimulator.pipe(debounceTime(1000)).subscribe(() => {
        this.triggeredSend();
      }
    )
  );
}


// map your send()-method
public send(): void {
  // uses an ever-changing value in order to always trigger the update
  this.rxjsSimulator.next(Date.now());
}


// have a sub-method that gets triggered by the subject
private triggeredSend(): void {
  this.message = {...this.message, room: this.room, sender: this.currentUser, createdAt: new Date()};
  this.sendMessage.emit(this.message);
  this.clearMessage();
}

// unsubscribe
ngOnDestroy(): void {
    this.subscription.unsubscribe();
}

Leave a Reply

(*) Required, Your email will not be published