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);
};
debounce() and . debounceTime() both execute the observable's code directly. Then if the Observable emits observer. next() multiple times, the subscribe() callback event will be called only one time.
debounce delays notifications emitted by the source Observable, but drops previous pending delayed emissions if a new notification arrives on the source Observable.
What is debounce? Debounce delays the processing of a function bound to a certain user input event until a certain amount of time has passed. In other words the function is only executed once per specific user input event, even it the event is triggered multiple times.
(electronics) To remove the small ripple of current that forms when a mechanical switch is pushed in an electrical circuit and makes a series of short contacts.
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:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With