Search code examples
javascriptangularrxjskendo-ui-angular2

Emit http requests + debounce on Kendo field changes


I have a method which is called everytime some input text is change. (Basically it is a search).
I want to delay post/get request so if user quickly types, only one request will be send to server.

I was thinking something like that:

public partnerFilterChange(value)
{
    if (this.partnersSubscriptions)
        this.partnersSubscriptions.unsubscribe();

    this.partnersSubscriptions = this.partnersService.list({ filter: value })
        .debounceTime(5000)
        .subscribe(partners =>
        {
            delete this.partnersSubscriptions;
            this.partners = partners;
        });
}

but it is not working.

Http request is executed immediately, not after 5 seconds. I also try delay instead debounceTime.

Edited:

I am using kendo drop down list component and its change event, so I have no control over the function call, only on subscribing to http request.


Solution

  • As per my comment. You can't use form.get('fieldName').valueChanges directly since you're using Kendo. But you CAN push the values received from Kendo to your own, custom observable, thus replicating the behavior of valueChanges:

    class AppComponent {
      // This is your own, custom observable that you'll subscribe to.
      // It will contain a stream of filter values received from Kendo.
      private _filterValues: Subject<string> = new Subject<string>();
    
      constructor() {
        // Start from your custom stream, debounce values, and run http query
        this._filterValues.asObservable()
          .debounceTime(400)
          .mergeMap(value => this.partnersService.list({ filter: value }))
          .subscribe(partners => this.partners = partners);
      }
    
      // This method is called by Kendo every time the field value changes.
      handleFilter(value) {
        // Push the value in the custom stream.
        this._filterValues.next(value);
      }
    }
    

    NB. This code assumes that this.partnersService.list() returns an observable.

    With this code, every time you update the field, the list of partners should be refreshed and the debounce should be applied. (I haven't tested the code, you might need to adapt it to your own use case.)