angulartypescriptrxjsangular15

Trigger Service With A Delay


Currently I am using Lodash decorator to delay a service call on drop down value change. In the select tag, I did something as follows:

(onSelectionChange)="logUserSearchData()"

In the TypeScript file, I've the following:

logUserSearchData() {
   logService();
}

@Debounce(10000)
logService() {
   this.logService().subscribe();
} 

In the above code snippet, the logService() is triggered after 10s whenever there's a change in drop down or value change. Is there a way in RxJS to do the same without using the Lodash decorator?


Solution

  • You have to move the code to the ngOnInit hook and then use debounceTime of rxjs to perform the debounce operation.

    We use a subject to emit values, which will be received on the ngOnInit and get debounced.

    private subject: Subject<void> = new Subject<void>();
    private sub: Subscription = new Subscription();
    
    ngOnInit() {
      this.sub.add(
        this.subject.pipe(
          debounceTime(500), 
          switchMap(() => this.logService()), // <- switches to the inner observable and discards still running operations of the method.
        ).subscribe()
      );
    }
    
    logUserSearchData() {
      this.subject.next();
    }
    
          
    ngOnDestroy() {
      this.sub.unsubscribe();
    }