RxJS 03 ๐ฃ Creation Operators โ Generating streams with of, from, fromEvent, interval, timer, defer, and fromFetch
While the Observable constructor is the most fundamental way to create a stream, it is often too verbose for daily tasks. RxJS provides a suite of “Creation Operators” that act as factory functions. These operators are the bridge between the non-reactive world of standard JavaScript and the reactive world of RxJS. They take existing data structuresโlike arrays, promises, events, or simple valuesโand wrap them in an Observable container so they can be processed through the RxJS pipeline.
Creation operators are distinct from pipeable operators. While pipeable operators (like map or filter) transform an existing stream, creation operators are the starting point. They are standalone functions that you import directly from the core rxjs package. They define how the stream begins, what values it initially emits, and how it handles its internal lifecycle.
In this chapter, we will explore the most commonly used creation operators. We will start with simple value emitters like of and from, move into time-based generators like interval and timer, and look at how to interface with the outside world using fromEvent and fromFetch. We will also examine the defer operator, which is essential for maintaining the “lazy” nature of Observables when dealing with code that might execute too early.
Understanding which creation operator to use is the first step in writing clean reactive code. Choosing the right starting point ensures that your data flows correctly, your errors are caught at the source, and your resources are managed efficiently without manual intervention.
Key point: Creation operators are the “entry points” into the RxJS ecosystem; they convert static data, arrays, events, and promises into Observables, providing a standardized interface for disparate data sources.
Why exists
The “Boilerplate” problem
Creating an Observable manually using the constructor requires writing the same setup logic repeatedlyโcalling next, complete, and defining teardown logic. Creation operators encapsulate this logic into single-function calls. Instead of 10 lines of code to wrap a click event, you use fromEvent(btn, 'click'), which handles the event listener attachment and removal automatically.
The “Input Heterogeneity” problem
In a standard web application, data comes from everywhere: local variables, arrays, remote APIs, DOM events, and Web Workers. Each has a different API. RxJS creation operators exist to “level the playing field.” By converting every source into an Observable at the start, you can use the same set of operators to process a mouse click as you would a database response.
The “Eager Promise” problem
JavaScript Promises are eager; they start executing as soon as they are created. This can lead to side effects running when you don’t want them to. Operators like from (when wrapping a promise factory) or defer allow you to wrap this eager logic in a lazy Observable, ensuring the operation only starts when someone actually subscribes.
The “Timing” problem
Manually managing intervals and timeouts is error-prone, especially when you need to clear them to prevent memory leaks. Creation operators like interval and timer provide a declarative way to handle time-based events. They integrate perfectly with the RxJS subscription model, ensuring that as soon as you unsubscribe, the underlying timer is destroyed.
The “Late Evaluation” problem
Sometimes you need to create an Observable that shouldn’t decide what data to emit until the exact moment of subscription. The defer operator exists specifically for this “just-in-time” creation. It allows you to produce a different Observable for every subscriber based on the current state of the application.
a. Static Data: of and from
The of and from operators are the most common ways to turn existing data into a stream. While they look similar, they handle their arguments very differently. The of operator takes a variable number of arguments and emits them one by one as they are.
import { of } from 'rxjs';
// Emits three separate values
const source$ = of(1, 2, 3);
source$.subscribe(val => console.log(val)); // 1, 2, 3
// Emits the array itself as ONE value
const arraySource$ = of([10, 20, 30]);
arraySource$.subscribe(val => console.log(val)); // [10, 20, 30]
The from operator is more intelligent. It accepts an “Observable-like” objectโan Array, a Promise, an Iterable, or even another Observableโand flattens it. If you pass an array to from, it iterates through the array and emits each element individually. If you pass a Promise, it waits for the promise to resolve and then emits the result.
import { from } from 'rxjs';
// Emits each element of the array individually
const arraySource$ = from([10, 20, 30]);
arraySource$.subscribe(val => console.log(val)); // 10, 20, 30
// Converts a Promise into an Observable
const promiseSource$ = from(fetch('https://api.example.com/data'));
promiseSource$.subscribe(response => console.log(response));
The choice between of and from depends on whether you want to emit the container (use of) or the contents of the container (use from).
b. Events and Time: fromEvent, interval, and timer
Interacting with the DOM and the clock are two of the most powerful use cases for RxJS. The fromEvent operator creates an Observable from any DOM element that supports addEventListener. It handles the listener lifecycle automatically.
import { fromEvent } from 'rxjs';
const btn = document.querySelector('#submit-btn');
const clicks$ = fromEvent(btn, 'click');
const sub = clicks$.subscribe(ev => console.log('Clicked!', ev));
// Calling sub.unsubscribe() automatically calls removeEventListener
For time-based logic, interval and timer are the standard tools. interval(ms) emits a sequence of ascending integers starting from 0 at the specified interval. It is infinite until unsubscribed. timer(delay, period) is more flexible: it waits for an initial delay and then optionally starts an interval based on the period.
import { interval, timer } from 'rxjs';
// Starts immediately, emits every 1000ms
const everySecond$ = interval(1000);
// Waits 3 seconds, emits once, and completes
const onceAfter3s$ = timer(3000);
// Waits 2 seconds, then emits every 500ms
const delayedInterval$ = timer(2000, 500);
These operators are preferred over setInterval because they can be easily composed with other operators like take(n) to create finite sequences without manual counters.
c. Advanced Creation: defer and fromFetch
The defer operator is a “factory for Observables.” It takes a function that returns an Observable. The key is that this function is only called at the moment of subscription. This is useful for ensuring that each subscriber gets fresh data or for wrapping logic that needs to be calculated “just in time.”
import { defer, of } from 'rxjs';
// Without defer, Date.now() is evaluated when the variable is defined
const staticDate$ = of(Date.now());
// With defer, Date.now() is evaluated when .subscribe() is called
const lazyDate$ = defer(() => of(Date.now()));
setTimeout(() => {
staticDate$.subscribe(v => console.log('Static:', v)); // Old timestamp
lazyDate$.subscribe(v => console.log('Lazy:', v)); // New timestamp
}, 2000);
For HTTP requests, RxJS 6+ introduced fromFetch. While you can wrap a standard fetch in from, fromFetch is specifically designed for the browser’s Fetch API. It provides built-in support for AbortController, meaning that if you unsubscribe from the Observable before the request finishes, the browser actually cancels the network request.
import { fromFetch } from 'rxjs/fetch';
import { switchMap } from 'rxjs/operators';
const data$ = fromFetch('https://api.github.com/users/rxjs').pipe(
switchMap(response => {
if (response.ok) return response.json();
return of({ error: true, message: response.status });
})
);
data$.subscribe(json => console.log(json));
Complete Example Session
// ============================================
// PART 1: SIMPLE VALUE EMISSION
// ============================================
import { of, from, fromEvent, interval, timer, defer } from 'rxjs';
import { take, map } from 'rxjs/operators';
const singleValues$ = of('A', 'B', 'C');
// Emits: 'A', then 'B', then 'C', then completes
// ============================================
// PART 2: ARRAY FLATTENING
// ============================================
const flattenedArray$ = from([1, 2, 3]);
// Emits: 1, then 2, then 3, then completes
// ============================================
// PART 3: PROMISE CONVERSION
// ============================================
const promise$ = from(Promise.resolve('Resolved!'));
// Emits: 'Resolved!', then completes
// ============================================
// PART 4: DOM EVENTS
// ============================================
// (Assuming a button exists in the environment)
const click$ = fromEvent(document, 'click');
// Emits: PointerEvent every time document is clicked
// ============================================
// PART 5: THE INFINITE INTERVAL
// ============================================
const numbers$ = interval(1000).pipe(take(5));
// Emits: 0, 1, 2, 3, 4 (one per second), then completes
// ============================================
// PART 6: THE FLEXIBLE TIMER
// ============================================
const alarm$ = timer(5000);
// Emits: 0 after 5 seconds, then completes
// ============================================
// PART 7: REPEATING TIMER
// ============================================
const heartbeat$ = timer(0, 2000);
// Emits: 0 immediately, then 1, 2, 3 every 2 seconds
// ============================================
// PART 8: DEFERRING EXECUTION
// ============================================
const random$ = defer(() => of(Math.random()));
// Every subscriber gets a different random number
// ============================================
// PART 9: ITERABLE CONSUMPTION
// ============================================
function* generator() {
yield 'Hi';
yield 'Bye';
}
const gen$ = from(generator());
// Emits: 'Hi', then 'Bye', then completes
// ============================================
// PART 10: COMPLEX COMPOSITION
// ============================================
const sequence$ = of(
of(1, 2),
from([3, 4])
);
// Emits two Observables as values (higher-order observable)
The example above walks through the most common creation scenarios, from simple constants and arrays to dynamic events, intervals, and deferred logic.
Quick Reference
Data Creation
| Operator | Input | Behavior |
|---|---|---|
of(...args) | Values | Emits each argument as a separate value. |
from(input) | Array/Promise/Iterable | Flattens the input and emits individual items. |
defer(factory) | Function returning Obs | Executes factory only on subscription. |
empty() | None | (Deprecated) Emits nothing, completes immediately. |
Time & Event Creation
| Operator | Arguments | Behavior |
|---|---|---|
interval(ms) | Number | Emits 0, 1, 2… every ms indefinitely. |
timer(d, p?) | Delay, Period | Emits after d, then every p. |
fromEvent(target, name) | Element, EventName | Wraps standard DOM/Node events. |
Network Creation
| Operator | Target | Key Benefit |
|---|---|---|
fromFetch(url) | URL String | Automatically handles AbortController. |
ajax(url) | URL String | Comprehensive AJAX wrapper (older style). |
Best Practices
โ Do This:
// Use 'from' for arrays you want to iterate
from([1, 2, 3]).subscribe(); // โ
// Use 'of' when you want to emit the whole array at once
of([1, 2, 3]).subscribe(); // โ
// Use 'fromFetch' for HTTP to get native cancellation
fromFetch('/api/data').subscribe(); // โ
// Use 'defer' to wrap non-lazy data sources
defer(() => getSomeData()).subscribe(); // โ
// Use 'take(n)' with 'interval' to prevent infinite loops
interval(1000).pipe(take(10)); // โ
โ Don’t Do This:
// Don't use 'of' for arrays if you intend to map each element
of([1, 2]).pipe(map(x => x * 2)); // โ (Result: [1, 2] * 2)
// Don't use 'fromEvent' without ever unsubscribing
fromEvent(d, 'click').subscribe(); // โ (Possible leak)
// Don't wrap a plain Promise in 'of'
of(Promise.resolve(1)); // โ (Emits the Promise object)
// Don't use interval(0) for synchronous loops
interval(0).pipe(take(1000)); // โ (Too much overhead)
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| of vs from Array | Using of when you wanted from. | Use from to emit array items individually. |
| Eager Promise | Creating the Promise outside the Observable. | Use defer or pass the Promise-returning function. |
| Zombie Intervals | interval continues forever in the background. | Use take, takeUntil, or manual unsubscribe. |
| fetch not canceled | Using from(fetch(...)) instead of fromFetch. | Use fromFetch for built-in cancellation support. |
| fromEvent context | The ‘this’ context of the event handler is lost. | Bind the context or use arrow functions. |
Real-World Examples
1. Single constant value
of(APP_CONFIG).subscribe();
2. Emitting an array’s contents
from(usersList).pipe(filter(u => u.active));
3. Converting a fetch promise
from(fetch('/api')).pipe(map(r => r.json()));
4. UI Click Stream
fromEvent(loginBtn, 'click');
5. Auto-save every 30 seconds
interval(30000).subscribe(() => saveDraft());
6. Delayed start of a process
timer(2000).subscribe(() => showWelcomeModal());
7. Fresh random data per sub
defer(() => of(generateToken()));
8. Converting a Generator
from(myFibonacciGenerator());
9. Responsive window resize
fromEvent(window, 'resize').pipe(debounceTime(200));
10. Simple Health Check (Poll)
timer(0, 10000).pipe(switchMap(() => checkStatus$));
Visual
of vs. from (Arrays)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ of([1, 2, 3]) โ
โ Emits the WHOLE array as one item โ
โ Output: [1, 2, 3] ----| โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ from([1, 2, 3]) โ
โ Emits EACH element as a separate item โ
โ Output: 1 ---- 2 ---- 3 ----| โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Timer vs. Interval
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ interval(1000) โ
โ Wait 1s: 0 -- Wait 1s: 1 -- Wait 1s: 2 ... โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ timer(3000, 1000) โ
โ Wait 3s: 0 -- Wait 1s: 1 -- Wait 1s: 2 ... โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Defer “Factory”
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DEFER FLOW โ
โ โ
โ Sub 1 โโโบ [Factory Function Runs] โโโบ Obs A (Data 1) โ
โ Sub 2 โโโบ [Factory Function Runs] โโโบ Obs B (Data 2) โ
โ โ
โ (Data is evaluated AT subscription time) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Simple Values | of(v1, v2) |
| Collections | from([a, b]) |
| Async Bridges | from(Promise) |
| UI Inputs | fromEvent(el, 'name') |
| Clock Logic | interval, timer |
| Late Binding | defer(() => source) |
| HTTP Native | fromFetch(url) |
| Completeness | Most emit and then auto-complete. |
Key takeaways:
- Use creation operators to enter the stream. They are the primary tool for converting standard JavaScript objects into Observables.
ofis for static arguments. It treats its arguments literally, even if they are arrays or promises.fromis for flattening. It looks inside the object (array, promise, iterable) and emits the contents.fromEventmanages listeners. It removes the need for manualaddEventListenerandremoveEventListenercalls.- Time operators are declarative.
intervalandtimerreplace the imperativesetIntervaland integrate with RxJS cancellation. defermaintains laziness. It ensures that code which might have side effects doesn’t run until a subscription is active.- Resource management is built-in. Nearly all creation operators handle their own cleanup when you call
.unsubscribe().
Remember: Don’t use the new Observable constructor if a creation operator already exists for your task. Operators like fromEvent and fromFetch are battle-tested and handle edge cases (like browser event cleanup and fetch abortion) that are easy to miss when writing custom wrappers.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!