10

I understand that Observable.debounce() can be used to process rapid fire form input. As Http GET also returns an Observable, I wonder it it is possible to debounce rapid http requests? I tried debounceTime() but it did not appear to do anything.

public getStuff(p1, area:string, p2:string): Observable<number> { 
   return this.http.get(some_url) 
   .map(r => r.json()) 
   .debounceTime(10000) 
  .catch(this.handleError); 
};
micronyks
  • 54,797
  • 15
  • 112
  • 146
Joseph Genchik
  • 1,821
  • 3
  • 15
  • 19

3 Answers3

11

The debounceTime allows to buffer events and only handle the last one after an amount of time.

It's useful in the context of inputs but it should be defined on the observable that triggers the event not on the one created for the HTTP request.

Here is a example on a control associated with an input that leverages the debounceTime operator:

@Component({
  (...)
  template: `
    <input [ngFormControl]="ctrl"/>
  `
})
export class MyComponent {
  constructor() {
    this.ctrl = new Control();
    this.ctrl.valueChanges
               .debounceTime(500)
               .distinctUntilChanged()
               .switchMap((value: string) => {
                 // Get data according to the filled value
                 return this.service.getData(entry);
               })
               .subscribe(data => {
                 // Update the linked list
                 this.list = data;
               });
  }
}

This article could also interest you:

Following the micronyks's comment, here is an additional link:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • In modern Angular you would have to place `debounceTime` and other functions inside `pipe(..)` call. I.e. : `...valueChanges.pipe(debounceTime(500), distinctUntilChanged(), switchMap(..)).subscribe(..);` – kolobok Sep 20 '21 at 17:25
4

You have to transform from subject observable into an http observable with switchMap like this:

observableObj$: Observable<any>;
subjectObj = new Subject();

 ngOnInit() {
    this.observableObj$ = this.subjectObj.pipe(
      debounceTime(1000),
      switchMap(() => {
        ...
        return this.http.get(some_url).map(r => r.json());
      }),
    );

    this.observableObj$.subscribe((data) => {
      // result of http get...
      ...
    });
}

getStuff() {
    this.subjectObj.next();
}
A. Morel
  • 9,210
  • 4
  • 56
  • 45
4

in Angular7:

import { Observable, of, timer } from 'rxjs';
import { catchError, retry, map, debounce } from 'rxjs/operators';

public getStuff(p1, area:string, p2:string): Observable<number> { 
   return this.http.get(some_url) 
   .pipe(
      debounce(() => timer(10000)),
      catchError(this.handleError)
   );
};
Emir Mamashov
  • 1,108
  • 9
  • 14