LiveLoveApp logo

Asynchronous

Asynchronous

As we have learned, like a plain old function in JavaScript, Observables are synchronous.

However, Observables can also be asynchronous.

Let's look at an example of an asynchronous Observable that fetches data from an API.

import { Observable } from 'rxjs';

console.log('before observable');

const observable = new Observable((subscriber) => {
  const request = new Request('https://reqres.in/api/users');
  fetch(request)
    .then((response) => response.json())
    .then((value) => {
      subscriber.next(value);
      subscriber.complete();
    })
    .catch((error) => {
      subscriber.error(error);
    });
});

observable.subscribe({
  next: (value) => console.log(value),
  error: (e) => console.error(e),
  complete: () => console.log('complete'),
});

console.log('after observable');

See example on codesandbox

In the code example above, we note the following order in the console:

  • before observable
  • after observable
  • response data
  • complete

This is because the fetch() is asynchronous; thus, we deliver the next notification asynchronously.

Takeaways

  • First, Observables can have multiple Observers and deliver multiple next notifications.
  • Second, Observables can provide an error notification when an error has occurred during the production of values.
  • Third, Observables can provide a complete notification when the production of values has ended.
  • Fourth, Observables can be synchronous or asynchronous.