Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJs dynamic debounceTime is not dynamic

Tags:

angular

rxjs

I've created an Angular directive which is applied to an input and emits its values with some delay (for search).

The code of this is following

@Directive({
    selector: '[search-field]'
})
export class SearchFieldDirective {
    @Input() searchFieldValueOutputDelay = 400;

    private _inputObservable$ = new Subject();

    @Output() searchValueUpdated = this._inputObservable$.asObservable().pipe(
        debounceTime(this.searchFieldValueOutputDelay),
        distinctUntilChanged(),
        tap(() => console.log('emit', this.searchFieldValueOutputDelay))
    );

    @HostListener('keyup', ['$event.target.value'])
    onChange(e) {
        console.log("change");
        this._inputObservable$.next(e);
    }
}

The problem is that searchFieldValueOutputDelay is taken only first time and therefore it has value of 400 and not the value I've provided on input.

<input (searchValueUpdated)="searchCard($event)" [searchFieldValueOutputDelay]="1000" type="search">

like image 499
Sergey Avatar asked Aug 01 '19 08:08

Sergey


1 Answers

The value for debounceTime is only evaluated once, on observable creation time.

To be able to dynamically update debounceTime, use debounce together with timer, like this :

@Output() searchValueUpdated = this._inputObservable$.asObservable().pipe(
        debounce(()=>timer(this.searchFieldValueOutputDelay)),
        distinctUntilChanged(),
        tap(() => console.log('emit', this.searchFieldValueOutputDelay))
    );
like image 132
Boyen Avatar answered Nov 15 '22 06:11

Boyen