Rxjs Operators are special type of functions that take input as an observable and then return an observable as an output that means Operators work with observable to make various kind of operations in angular or JavaScript.
In this section we are going to differentiate the debounce time and throttle time operator in rxjs, they both work pretty much similar but can make big difference in the logic.
We use rxjs operators to make application more functional like if there is no delay needed in ongoing application then the application supposed to skip that delay to perform good. so we have various operators in rxjs which we can use in angular , JavaScript and react applications so that an application can have right thing at right time.
Debounce Time
searchTextChanged = new Subject<string>();
constructor(private http:Http) {}
ngOnInit(): void {
this.subscription = this.searchTextChanged
.debounceTime(1000)
.distinctUntilChanged()
.mergeMap(search => this.getValues())
.subscribe(() => { });
}
getValues() {
return this.http.get("https://www.example.com/search/?q="+this.q)
.map(
(res:Response) => {
const studentResult = res.json();
console.log(studentResult);
if(studentResult.success) {
this.results = studentResult.data;
} else {
this.results = [];
}
}
);
}
search($event) {
this.searchTextChanged.next($event.target.value);
}
We often use distinctUntilChanged along with debounceTime where we can only get unique values in subscription, distinctUntilChanged is used to only get unique values until the debounce time happens.
Throttle Time
@ViewChild('scroller') scroller: CdkVirtualScrollViewport;
this.scroller.elementScrolled().pipe(
map(() => this.scroller.measureScrollOffset('bottom')),
filter(([y1, y2]) => (y2 < y1 && y2 < 140)),
throttleTime(200)
).subscribe(() => {
this.fetchMore();
}
0 Comments