Here are some examples of domains in which observables are particularly useful.
Observables can simplify the implementation of type-ahead suggestions. Typically, a type-ahead has to do a series of separate tasks:
Writing this in full JavaScript can be quite involved. With observables, you can use a simple series of RxJS operators:
import { fromEvent, Observable } from 'rxjs'; import { ajax } from 'rxjs/ajax'; import { debounceTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators'; const searchBox = document.getElementById('search-box') as HTMLInputElement; const typeahead = fromEvent(searchBox, 'input').pipe( map(e => (e.target as HTMLInputElement).value), filter(text => text.length > 2), debounceTime(10), distinctUntilChanged(), switchMap(searchTerm => ajax(`/api/endpoint?search=${searchTerm}`)) ); typeahead.subscribe(data => { // Handle the data from the API });
Exponential backoff is a technique in which you retry an API after failure, making the time in between retries longer after each consecutive failure, with a maximum number of retries after which the request is considered to have failed. This can be quite complex to implement with promises and other methods of tracking AJAX calls. With observables, it is very easy:
import { timer } from 'rxjs'; import { ajax } from 'rxjs/ajax'; import { retry } from 'rxjs/operators'; export function backoff(maxTries: number, initialDelay: number) { return retry({ count: maxTries, delay: (error, retryCount) => timer(initialDelay * retryCount ** 2), }); } ajax('/api/endpoint') .pipe(backoff(3, 250)) .subscribe(function handleData(data) { /* ... */ });
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/practical-observable-usage