1

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?

2 Answers 2

5

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Though the accepted answer works, I'd suggest not using a Subject but instead do it in a more reactive way.

You can easily capture the click event with the fromEvent function, debounce the event and then do whatever you want, instead of having to keep track of an observable.

Just get your button with a @ViewChild('idToMyButton') button: ElementRef; and then start listen to the click events with fromEvent(button.nativeElement, 'click');

The fromEvent will emit any time the button is clicked, so you can easily debounce it just like

fromEvent(button.nativeElement, 'click').pipe(
    debounceTime(250),
    tap(() => {
        // Do what needs to be done on click
    }),
    takeUntil(this.destroyed$) // Don't forget to unsubscribe
).subscribe();

// For cleanup purposes
ngOnDestroy() {
    this.destroyed$.next();
    this.destroyed$.complete();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.