#rxjs
#tutorial
#beginner
Day 2: Creation Operators
Day 2: Creation Operators
Manually creating Observables with new Observable() is tedious. RxJS provides helper functions called Creation Operators to make this easy.
1. of
Creates an observable from a list of arguments. It emits them one by one and then completes instantly.
import { of } from 'rxjs';
of(1, 2, 3).subscribe(console.log);
// Output: 1, 2, 3
2. from
Converts an Array, Promise, or Iterable into an Observable.
import { from } from 'rxjs';
const array = ['Alice', 'Bob', 'Charlie'];
from(array).subscribe(console.log);
// Output: Alice, Bob, Charlie
Promise Example:
const promise = fetch('/api/user');
from(promise).subscribe(user => console.log(user));
3. fromEvent
Creates an observable from DOM events. This is huge for UI programming.
import { fromEvent } from 'rxjs';
// Listen to clicks on the document
const clicks$ = fromEvent(document, 'click');
clicks$.subscribe(event => {
console.log('Clicked at:', event.clientX, event.clientY);
});
4. interval & timer
Great for polling or delays.
interval(1000): Emits 0, 1, 2… every 1000ms. Infinite.timer(2000): Emits 0 after 2000ms, then completes.timer(2000, 1000): Waits 2s, then emits every 1s.
import { interval } from 'rxjs';
const subscription = interval(1000).subscribe(num => {
console.log(num);
});
// Don't forget to unsubscribe!
setTimeout(() => subscription.unsubscribe(), 5000);
Homework for Day 2:
- Use
fromEventto listen to “keyup” events on an input field. - Log the key that was pressed.
- Use
ofto emit your name and log it.
Tomorrow, we start transforming data with Pipeable Operators!