AI Hints
Home›Angular Tutorial›RxJS Basics, map and filter and Search with debounceTime
Angular · Lesson 100 of 120

RxJS Basics

Streams of values.

⏱ 2 min read▶ Video at 2:00:56🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Observables come from a library called RxJS. It ships with Angular. Let's learn the few parts of it you'll use most.

  • Observables come from RxJS
  • Ships with Angular
  • The useful parts

Making observables

Of sends a few fixed values. From sends each item of an array. Interval sends a number, again and again, on a timer. And a dollar sign, at the end of a name, is a habit, that marks an observable.

keyvalue
of(a, b)fixed values
from([ ... ])each array item
interval(ms)a timer
books$the $ marks an observable

Three sources

Of sends two titles. From sends each price in the array. Interval counts every hundred milliseconds, and take stops it after three. Run it. Each source delivered its values, and interval stopped at two.

main.tstypescript
import { of, from, interval, take } from 'rxjs';

of('Dune', 'Emma').subscribe(title => console.log('of:', title));

from([9.99, 6.99]).subscribe(price => console.log('from:', price));

interval(100).pipe(take(3)).subscribe(n => console.log('interval:', n));
Output
of: Dune
of: Emma
from: 9.99
from: 6.99
interval: 0
interval: 1
interval: 2
Also uses _mode
ts

A Subject

A subject is an observable, that we can push values into, with next. The header subscribes first, and sees Dune. Then the basket subscribes, and both see Emma. Run it. The basket missed Dune, because it subscribed later.

main.tstypescript
import { Subject } from 'rxjs';

const added$ = new Subject<string>();

added$.subscribe(title => console.log('Header saw', title));
added$.next('Dune');

added$.subscribe(title => console.log('Basket saw', title));
added$.next('Emma');
Output
Header saw Dune
Header saw Emma
Basket saw Emma
Also uses _mode
ts

Summary

Of, from, and interval make observables, and subjects let us push values in, with next. Next, transforming values, with operators.

Key takeaways
  • of, from, interval
  • Subject
  • next()
Next up: map and filter — operators