4

I'm trying to use debounceTime on an Angular 5 function but I'm not sure how to use it. When I built a search function I could use it, because it was bind to the changes made on that input value, like this:

this.search
    .debounceTime(400)
    .distinctUntilChanged()
    .takeUntil(this.onDestroy)
    .subscribe((model) => {
        return this.filterArray(model);
    });

But now I want to apply it to a function, this function is called from many places, and send an event to the database via http post, something like this:

private saveData(): void {
    this.http.post('event/url', data).takeUntil(this.onDestroy).subscribe((response: Response) => {
        // -
    }, error => {
        // -
    });
}

Is there a way to do it like saveData().debounceTime() Or do I need to do it other way?

celsomtrindade
  • 4,501
  • 18
  • 61
  • 116

3 Answers3

7

I'm not sure but something like this might work:

$save: Subject<void> = new Subject<void>();

In your constructor or init:

this.$save
  .debounceTime(400)
  .switchMap(() => this.http.post(...post params))
  .subscribe(..Do something);

Your save method:

saveData(){
    this.$save.next();
}
Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116
1

Putting this here for

// "rxjs": "^6.2.0",
//import { Subject } from 'rxjs';
//import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
...
export class SomeClass {    
    ...
    $subject: Subject<void> = new Subject<void>();


    constructor() {
        this.$subject.pipe(debounceTime(2000), distinctUntilChanged());
    }

    onSomeMethod(event: string) {
        this.$subject.next(this.runMethod(event));
    }

    runMethod(event: any) {
        // do stuff
        console.log(event);
    }
    ...
}
Don Thomas Boyle
  • 3,055
  • 3
  • 32
  • 54
1

// "rxjs": "^6.3.3"
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
...
export class SomeClass {    
    ...
    $subject: Subject<string> = new Subject<string>();


    constructor() {
        this.$subject.pipe(debounceTime(1000)).subscribe((event: string) => runMethod(event));
    }

    onSomeMethod(event: string) {
        this.$subject.next(event);
    }

    private runMethod(event: string) {
        // do stuff
        console.log(event);
    }
    ...
}