← Back to Angular, page 9

angular-0166 · Easy fresher

How do the RxJS creation functions of, from, interval and timer differ, and when do you use each?

of emits the values you list and completes. from converts an array, promise or iterable to an observable. interval emits increasing numbers on a repeating delay and never completes. timer waits for a delay, emits 0, and can repeat if you give a second argument. Timers keep running until you unsubscribe.

Full answer

Creation functions make an observable from something that is not an observable. You import them from rxjs (not from rxjs/operators).

  • of(a, b, c): emits each argument, then completes. of([1, 2]) emits one value, the array. Use it for test data, default values or returning a fixed result from a catchError.
  • from(source): converts an array, a string, a Set, a Promise or another iterable. from([1, 2, 3]) emits three values. from(fetchPromise) emits the resolved value once and completes. The difference with of: from spreads the input, of takes the arguments as they are.
  • interval(ms): emits 0, 1, 2 ... every ms milliseconds, after waiting ms for the first one. It never completes, so you must stop it with take, takeUntil, takeUntilDestroyed or unsubscribe.
  • timer(due): waits due ms, emits 0 and completes. timer(0, 1000) emits at once and then every second (the second argument is the period), so it is interval with an initial delay you choose. timer(5000) is a good "do this once after 5 seconds" tool.

Other useful ones: EMPTY (completes at once), NEVER, throwError(() => new Error('x')), fromEvent(button, 'click') for DOM events, defer(() => from(fetchData())) to delay creating the source until subscription (a promise starts immediately when it is created, but defer waits).

Notes:

  • Synchronous sources (of, from(array)) emit during subscribe, before the next line of code runs.
  • Timers need cleanup. In a component use takeUntilDestroyed(). A timer that is never unsubscribed keeps the app unstable, which delays server rendering and service worker registration.
  • interval uses setInterval, so a busy browser can delay ticks. Do not use it as a precise clock.
typescript
import { defer, from, interval, of, take, timer } from 'rxjs';

of([1, 2, 3]).subscribe((v) => console.log('of array:', JSON.stringify(v)));
from([1, 2, 3]).subscribe((v) => console.log('from array:', v));
from(Promise.resolve('loaded')).subscribe((v) => console.log('from promise:', v));

let started = false;
const lazy$ = defer(() => {
  started = true;
  return of('created on subscribe');
});
console.log('defer created, started =', started);
lazy$.subscribe((v) => console.log(v, '| started =', started));

interval(20).pipe(take(3)).subscribe({
  next: (n) => console.log('interval', n),
  complete: () => console.log('interval complete'),
});
timer(10, 25).pipe(take(2)).subscribe((n) => console.log('timer', n));

RxJS 7.8. The script was run in Node 24 twice with identical output. Time based values print as ordered events, and it exits when the timers are done.

Key points

  • `of` lists values, `from` spreads an array or converts a promise or iterable.
  • `interval` repeats and never completes. `timer` waits first and can repeat with a second argument.
  • Always stop timers with `take`, `takeUntil` or `takeUntilDestroyed`.
  • `defer` delays creation until subscription.

Common mistakes

  • Using `of([1, 2, 3])` and expecting three values.
  • Forgetting to stop `interval`.
  • Creating a promise early and thinking `from(promise)` delays it.

Follow-ups

  • What is the difference between `timer(0, 1000)` and `interval(1000)`?
  • When do you use `defer`?
  • Why is a timer a problem for server rendering?

Tips

  • Give the `of([1,2,3])` versus `from([1,2,3])` example.
  • Mention cleanup for timers.
  • Mention `defer` for promises.

Evaluation rubric

  • Describes the four functions correctly.
  • Shows the `of` versus `from` difference.
  • Handles cleanup and timing details.