Course contentsShow
← JavaScript
Lesson 2129 of 2,72344. Reactive PatternsFree lesson

Creating Observables

Using `of`, `from`, `interval`, and the `Observable` constructor to create streams.

Creating Observables

You'll learn how to create Observable streams using RxJS's built-in creation functions and the Observable constructor.

The Core Idea

Creating an Observable is like setting up a pipeline that will emit values over time. RxJS provides several convenient factory functions to create Observables from different sources: static values, arrays, time intervals, or custom logic.

Creation Methods

of() – Emit Fixed Values

The of() function creates an Observable that emits the values you provide, then completes:

import { of } from 'rxjs';

const numbers$ = of(1, 2, 3);
numbers$.subscribe(value => console.log(value));
// Logs: 1, 2, 3

Think of of() as a conveyor belt that delivers exactly the items you placed on it.

from() – Convert Iterables

The from() function converts arrays, promises, or other iterables into Observables:

import { from } from 'rxjs';

const fromArray$ = from([10, 20, 30]);
fromArray$.subscribe(value => console.log(value));
// Logs: 10, 20, 30

interval() – Emit on a Timer

The interval() function emits sequential numbers at a fixed time interval:

import { interval } from 'rxjs';

const timer$ = interval(1000); // Emits every 1000ms
timer$.subscribe(value => console.log(value));
// Logs: 0, 1, 2, 3... (every second)

The Observable Constructor

For custom logic, use the constructor with a subscribe function:

import { Observable } from 'rxjs';

const custom$ = new Observable(subscriber => {
  subscriber.next('Hello');
  subscriber.next('World');
  subscriber.complete();
});

custom$.subscribe(value => console.log(value));
// Logs: Hello, World

Key Takeaway: RxJS provides of() for static values, from() for iterables, interval() for time-based emissions, and the Observable constructor for custom streaming logic—each creating a pipeline that pushes values to subscribers.