LiveLoveApp logo

Solution - Observer

Solution

import { Observable } from 'rxjs';

const observable = new Observable((subscriber) => {
  let i = 0;
  const id = setInterval(() => {
    if (i === 10) {
      subscriber.complete();
    }
    subscriber.next(i++);
  }, 1000);

  return () => {
    clearTimeout(id);
  };
});

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

See solution on codesandbox

Let's review the solution code above:

  • First, we create a new Observable instance.
  • We specify the subscriber function that is invoked with the subscriber.
  • We set the variable i to 0. We'll use the let keyword so that we can mutate the value within the callback for the interval.
  • Every 1s we deliver a next notification to the observers using the next() method.
  • After 10 seconds we complete the Observable by invoking the complete() method on the subscriber.
  • We return a teardown function that clears the timeout.
  • Finally, we subscribe to the Observable and provide an Observer.