Sub topic 2
Creating Observables with of, from, fromEvent, and interval
The previous chapter built an observable by hand with new Observable(). In practice you rarely do that. RxJS ships creation functions, which are factory functions that wrap a common data source in an observable for you. This chapter assumes you know TypeScript generics, arrow functions, Promises, and the observer/subscription model from the last chapter.
Picking a Creation Function by Source
Each function fits one kind of source. Choose it based on where your values come from.
| Function | Emits | Completes? | Timing |
|---|---|---|---|
| `of(a, b, c)` | Each argument once | Yes | Synchronous |
| `from(array)` | Each element | Yes | Synchronous |
| `from(promise)` | The resolved value | Yes | Asynchronous |
| `fromEvent(target, name)` | Each event | No | Asynchronous |
| `interval(ms)` | 0, 1, 2, ... | No | Asynchronous |
Seeing Them Run
This script runs in Node or a browser console with rxjs installed.
import { of, from, interval, take } from 'rxjs';
of(1, 2, 3).subscribe(v => console.log('of:', v));
from([10, 20, 30]).subscribe(v => console.log('from array:', v));
from(Promise.resolve('ready')).subscribe(v => console.log('from promise:', v));
interval(500)
.pipe(take(3))
.subscribe({
next: n => console.log('interval:', n),
complete: () => console.log('interval done'),
});
console.log('end of script');The output order shows the timing rules. The of and from(array) values print before end of script because they emit synchronously during subscribe. The promise value prints right after, on the microtask queue. The interval values arrive every 500 ms. take(3) makes the interval complete after three values, which is why interval done appears.
Listening to Events with fromEvent
fromEvent adds an event listener when you subscribe and removes it when you unsubscribe.
import { fromEvent, map } from 'rxjs';
const clicks$ = fromEvent<MouseEvent>(document, 'click').pipe(
map(event => ({ x: event.clientX, y: event.clientY }))
);
const sub = clicks$.subscribe(pos => console.log('clicked at', pos));
// Later, when the listener is no longer needed:
setTimeout(() => sub.unsubscribe(), 10000);In Angular you would usually reach for template event bindings or HostListener first. fromEvent pays off when you want to compose events with operators, for example throttling scroll or resize events.
Common Mistakes
of(array)vsfrom(array).of([1, 2, 3])emits the whole array as one value.from([1, 2, 3])emits three separate numbers.- Expecting async behaviour from
of. Code aftersubscriberuns after allofvalues have been emitted, not before them. - Leaving infinite streams open.
intervalandfromEventnever complete on their own. If nothing unsubscribes or limits them, they keep timers and listeners alive after a component is destroyed. A later chapter coverstakeUntilDestroyedand the async pipe for this. - Assuming
from(promise)is lazy. The promise starts running when you create it, not when you subscribe. Usedefer(() => fetchData())if the work should start on subscription.
Exercise
What does this log, and in what order? from(['a', 'b']).subscribe(v => console.log(v)); of(['c', 'd']).subscribe(v => console.log(v)); console.log('x');
Show answer
It logs a, then b, then ['c', 'd'] as a single array, then x. Both from with an array and of emit synchronously. of treats the array as one value, while from emits each element separately.
Exercise
A component subscribes to interval(1000) in ngOnInit and never unsubscribes. What happens when the user navigates away?
Show answer
The interval keeps firing after the component is destroyed, because interval never completes. The callback holds a reference to the component, so the component cannot be garbage collected. That is a memory leak. Limit the stream with an operator such as take, or tie it to the component's lifetime.