Sub topic 2
Creating Observables with of, from, fromEvent, and interval
In the previous chapter you built an observable by hand with new Observable(...). That works, but you will rarely need it in practice. RxJS ships creation functions that wrap common sources for you: fixed values, arrays, promises, DOM events, and timers. Each one produces a correctly behaved observable with the teardown already written.
This chapter assumes you are comfortable with TypeScript generics and arrow functions, Promises, and basic Angular components. It also assumes you know what subscribing means and why unsubscribe() matters, from the previous chapter. All examples use RxJS 7 or later, where creation functions are imported directly from 'rxjs'.
The Four Workhorses at a Glance
| Function | Source | Emits | Completes? | Sync or async |
|---|---|---|---|---|
| `of(a, b, c)` | Values you list as arguments | Each argument, in order | Yes, right after the last value | Synchronous |
| `from(x)` | Array, iterable, Promise, or another observable | Each element, or the resolved value | Yes, when the source ends | Sync for arrays and iterables, async for Promises |
| `fromEvent(target, name)` | DOM element, document, window, or Node emitter | Each event object | Never on its own | Async |
| `interval(ms)` | A timer | 0, 1, 2, ... every `ms` milliseconds | Never on its own | Async |
The "Completes?" column matters most. An observable that completes cleans itself up. An observable that never completes, like the ones from fromEvent and interval, keeps running until you unsubscribe.
of: Emitting Fixed Values
of takes any number of arguments and emits each one, then completes.
import { of } from 'rxjs';
console.log('before');
of(1, 2, 3).subscribe({
next: value => console.log('value', value),
complete: () => console.log('complete'),
});
console.log('after');Output:
before
value 1
value 2
value 3
complete
afterAll three values and the completion arrive before after prints. Observables are not asynchronous by default. of delivers everything synchronously during the subscribe() call. This surprises people who assume every observable behaves like a Promise.
In Angular, of is most useful for fallback values and test doubles. A service stub can return of([{ id: 1, name: 'Ada' }]) in place of an HTTP call, and the consumer's code doesn't change.
Common error: of with an array
import { of, from } from 'rxjs';
of([1, 2, 3]).subscribe(v => console.log(v)); // [1, 2, 3] (one emission)
from([1, 2, 3]).subscribe(v => console.log(v)); // 1, then 2, then 3of emits each argument as is, so an array argument arrives as one value. If you want the elements emitted one at a time, use from. Both versions are correct. They describe different streams, and the type tells you which one you have: Observable<number[]> versus Observable<number>.
from: Converting Existing Things
from turns something that already exists into an observable. It accepts arrays, any iterable (including strings, Map, Set, and generators), Promises, and other observable-like objects.
import { from } from 'rxjs';
from('abc').subscribe(ch => console.log(ch)); // a, b, c
from(new Map([['x', 1], ['y', 2]])).subscribe(entry => console.log(entry));
// ['x', 1], ['y', 2]
from(Promise.resolve(42)).subscribe({
next: v => console.log('resolved', v),
complete: () => console.log('promise stream complete'),
});With a Promise, from emits the resolved value once and then completes. If the Promise rejects, the observable sends an error notification. That means a single error callback or error operator handles both observable and Promise failures.
The Promise branch is asynchronous because Promise callbacks always run in a later microtask. The array and string branches are synchronous, just like of.
Gotcha: Promises are eager
A Promise starts its work when it is created, not when someone subscribes. Wrapping it in from does not make it lazy.
import { from, defer } from 'rxjs';
function loadSettings(): Promise<string> {
console.log('request sent');
return new Promise(resolve => setTimeout(() => resolve('dark-mode'), 100));
}
// Eager: "request sent" logs immediately, even with no subscriber.
const eager$ = from(loadSettings());
// Lazy: loadSettings runs once per subscription, only when subscribed.
const lazy$ = defer(() => from(loadSettings()));
lazy$.subscribe(v => console.log('lazy got', v));
lazy$.subscribe(v => console.log('lazy got again', v));eager$ sends one request at definition time, and every subscriber shares that single result. lazy$ sends a new request for each subscriber, at the moment it subscribes. defer takes a factory function and calls it on every subscribe. Use defer when the source should behave like a normal cold observable. This applies, for example, when you wrap a third-party SDK that returns Promises and you want a retry to actually re-run the call.
fromEvent: Streams of Events
fromEvent(target, eventName) calls addEventListener when you subscribe and removeEventListener when you unsubscribe. That teardown is the main reason to use it over a raw listener.
import { Component, ElementRef, OnDestroy, AfterViewInit, viewChild } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
@Component({
selector: 'app-click-counter',
standalone: true,
template: `
<button #btn>Click me</button>
<p>Clicks: {{ clicks }}</p>
`,
})
export class ClickCounterComponent implements AfterViewInit, OnDestroy {
private button = viewChild.required<ElementRef<HTMLButtonElement>>('btn');
private sub?: Subscription;
clicks = 0;
ngAfterViewInit(): void {
this.sub = fromEvent<MouseEvent>(this.button().nativeElement, 'click')
.subscribe(() => this.clicks++);
}
ngOnDestroy(): void {
this.sub?.unsubscribe();
}
}Note these points:
- The element must exist before you call
fromEvent. A view child is only available after the view initializes, so this example subscribes inngAfterViewInit, not in the constructor. - The generic
<MouseEvent>types the emitted value. Without it you get a genericEvent. - The stream never completes. Without the
ngOnDestroycleanup, the listener and the component it references stay in memory. A later chapter replaces this manual cleanup withtakeUntilDestroyed.
For global targets you can pass document or window directly, for example fromEvent(window, 'resize'). Those targets outlive every component, so forgetting to unsubscribe from them is the most common leak in Angular apps.
interval and timer: Streams of Time
interval(ms) emits an increasing counter: 0, then 1, then 2, one value every ms milliseconds. The first value arrives after one full period, not immediately.
import { interval, timer } from 'rxjs';
const start = Date.now();
const elapsed = () => `${Date.now() - start}ms`;
const everySecond = interval(1000).subscribe(n => console.log('interval', n, elapsed()));
// interval 0 ~1000ms, interval 1 ~2000ms, ...
const soonThenEverySecond = timer(0, 1000).subscribe(n => console.log('timer', n, elapsed()));
// timer 0 ~0ms, timer 1 ~1000ms, ...
const once = timer(2500).subscribe({
next: () => console.log('one-shot fired', elapsed()),
complete: () => console.log('one-shot complete'),
});
setTimeout(() => {
everySecond.unsubscribe();
soonThenEverySecond.unsubscribe();
console.log('stopped', elapsed());
}, 3500);timer has two forms:
timer(due)emits0once afterduemilliseconds, then completes. It is the observable version ofsetTimeout.timer(due, period)waitsduemilliseconds, then ticks everyperiodmilliseconds.timer(0, 1000)gives polling that fires right away, whichintervalcannot do.
Each subscription to interval starts its own timer at zero. Two subscribers do not share a counter. Chapter 13 explains this cold behavior and how to share a single source.
Gotcha: intervals in services
An interval subscribed inside a providedIn: 'root' service lives as long as the application does. That is fine for an app-wide clock. It becomes a problem when a component starts a polling subscription in a service method and nothing ever stops it. Every visit to that page then adds another timer. Return the observable from the service and let the component own the subscription.
Edge Cases Worth Knowing
| Situation | Behavior |
|---|---|
| `of()` with no arguments | Completes immediately without emitting. `EMPTY` does the same. |
| `from([])` | Completes immediately without emitting. |
| `from` on a rejected Promise | Sends `error` with the rejection reason. Nothing is emitted. |
| `fromEvent(null, 'click')` | Throws `TypeError: Invalid event target` when you subscribe. |
| `interval(0)` | Ticks as fast as the scheduler allows. Avoid it in production code. |
| `of(undefined)` | Emits `undefined` once. This is a value, not "no value". |
The same idea runs through all of these. Synchronous sources like of and from(array) finish before subscribe() returns. Event and timer sources keep running until you stop them.
Exercise
A teammate writes of(this.userIds).subscribe(id => this.load(id)), where userIds is a string array, and complains that load receives an array. What is wrong, and what is the fix?
Show answer
of emits each argument as one value, so the whole array arrives as a single emission. Use from(this.userIds) to emit each ID separately. The resulting type changes from Observable<string[]> to Observable<string>.
Exercise
You wrap a Promise-returning SDK call as from(sdk.fetchProfile()) and later add retry(3). When the call fails, the logs show only one network request. Why, and how do you make retries actually re-run the call?
Show answer
The Promise was created once when the line ran, and from replays that same settled Promise on every resubscription, so the failure repeats without a new request. Wrap the call in defer(() => from(sdk.fetchProfile())) so each subscription, including each retry, calls the SDK again.
Exercise
You need to poll an endpoint, with the first check right away and every 5 seconds after that. Which creation function and arguments do you use, and what must the component do?
Show answer
Use timer(0, 5000), because interval(5000) would wait 5 seconds before the first tick. The stream never completes, so the component must unsubscribe when it is destroyed, either manually in ngOnDestroy or with takeUntilDestroyed or the async pipe.