Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 217
Bruno Bruzzano Avatar asked Feb 15 '26 03:02

Bruno Bruzzano


1 Answers

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.

like image 194
LLai Avatar answered Feb 16 '26 16:02

LLai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!