2

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?

1 Answer 1

1

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

6 Comments

Alright @Naren Murali, will this work with `onSelectionChange' event of the drop down box as I require that to work with it at the same time?
@user8512043 updated my answer, forgot to add the method that fires for onSelectionChange event
See this if you can make it work - stackoverflow.com/questions/79175167/… @Naren Murali. Thanks for all the efforts.
You should consider using takeUntilDestroyed, which allows you to remove the dedicated sub property and eliminates the need for an ngOnDestroy method in this case.
@TomS sure will incorporate going forward
|

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.