Bruno Bruzzano
Bruno Bruzzano

Reputation: 477

Angular & Observable debounceTime

Into an Angular 4 project, I have a function (let's call it reload()) that could be called by other functions (let's call them A() and B()) at any time. I would like to debounce the execution of reload() till X time (ie. msecs) passed from the last call of A() or B(). I was taking a look at the Rx.Observable.debounce and Rx.Observable.debounceTime functions but I did not understand if they really can help me with that or not.

An example:

time 0ms: A() gets executed and it calls reload()
time 200ms: B() calls executed and it calls reload()
Since X is set to 500ms, reload() should be called only once and after 500ms.

Upvotes: 2

Views: 3714

Answers (1)

LLai
LLai

Reputation: 13396

You can use a Subject with debounceTime. So have both functions A & B send a value to the subject. Then debounce the subject stream so only values are emitted after x time has passed.

// component.ts
subject$ = new Subject();
stream$;

constructor(){
    this.stream$ = this.subject$.debounceTime(1000);
}

A(){
    this.subject$.next('some value');
}
B(){
    this.subject$.next('some value');
}

ngOnInit(){
    this.stream$.subscribe(res => {
        this.reload();
    });
}

Here is a stack blitz demoing this.

Upvotes: 8

Related Questions