Help Angular by taking a 1 minute survey!Go to surveyHome

Practical observable usage

Here are some examples of domains in which observables are particularly useful.

Type-ahead suggestions

Observables can simplify the implementation of type-ahead suggestions. Typically, a type-ahead has to do a series of separate tasks:

  • Listen for data from an input.
  • Trim the value (remove whitespace) and make sure it’s a minimum length.
  • Debounce (so as not to send off API requests for every keystroke, but instead wait for a break in keystrokes).
  • Don’t send a request if the value stays the same (rapidly hit a character, then backspace, for instance).
  • Cancel ongoing AJAX requests if their results will be invalidated by the updated results.

Writing this in full JavaScript can be quite involved. With observables, you can use a simple series of RxJS operators:

import { fromEvent } from 'rxjs'; import { ajax } from 'rxjs/ajax'; import { map, filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; const searchBox = document.getElementById('search-box'); const typeahead = fromEvent(searchBox, 'input').pipe( map((e: KeyboardEvent) => e.target.value), filter(text => text.length > 2), debounceTime(10), distinctUntilChanged(), switchMap(() => ajax('/api/endpoint')) ); typeahead.subscribe(data => { // Handle the data from the API });
Typeahead
      
      
  1. import { fromEvent } from 'rxjs';
  2. import { ajax } from 'rxjs/ajax';
  3. import { map, filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
  4.  
  5. const searchBox = document.getElementById('search-box');
  6.  
  7. const typeahead = fromEvent(searchBox, 'input').pipe(
  8. map((e: KeyboardEvent) => e.target.value),
  9. filter(text => text.length > 2),
  10. debounceTime(10),
  11. distinctUntilChanged(),
  12. switchMap(() => ajax('/api/endpoint'))
  13. );
  14.  
  15. typeahead.subscribe(data => {
  16. // Handle the data from the API
  17. });

Exponential backoff

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 { pipe, range, timer, zip } from 'rxjs'; import { ajax } from 'rxjs/ajax'; import { retryWhen, map, mergeMap } from 'rxjs/operators'; function backoff(maxTries, ms) { return pipe( retryWhen(attempts => zip(range(1, maxTries), attempts) .pipe( map(([i]) => i * i), mergeMap(i => timer(i * ms)) ) ) ); } ajax('/api/endpoint') .pipe(backoff(3, 250)) .subscribe(data => handleData(data)); function handleData(data) { // ... }
Exponential backoff
      
      
  1. import { pipe, range, timer, zip } from 'rxjs';
  2. import { ajax } from 'rxjs/ajax';
  3. import { retryWhen, map, mergeMap } from 'rxjs/operators';
  4.  
  5. function backoff(maxTries, ms) {
  6. return pipe(
  7. retryWhen(attempts => zip(range(1, maxTries), attempts)
  8. .pipe(
  9. map(([i]) => i * i),
  10. mergeMap(i => timer(i * ms))
  11. )
  12. )
  13. );
  14. }
  15.  
  16. ajax('/api/endpoint')
  17. .pipe(backoff(3, 250))
  18. .subscribe(data => handleData(data));
  19.  
  20. function handleData(data) {
  21. // ...
  22. }