We use cookies to enhance your experience on the site
CodeWorlds

RxJS in Angular - Ninja Scouts

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming - like a network of ninja scouts observing the terrain and instantly reporting events to headquarters.

What is Reactive Programming?

It is a paradigm based on data streams and change propagation:

  • Streams - sequences of events spread over time
  • Observers - react to every event in the stream
  • Operators - transform, filter, combine streams

Observable - Data Stream

An Observable is an "observable" sequence of values - like a ninja watching a castle and reporting every movement:

1import { Observable, of, from, interval, fromEvent } from 'rxjs';
2
3// Creating an Observable from values
4const numbers$ = of(1, 2, 3, 4, 5);  // Emits values and completes
5
6// From an array
7const fromArray$ = from([1, 2, 3]);
8
9// Timer - emits every second
10const timer$ = interval(1000);  // 0, 1, 2, 3...
11
12// From DOM events
13const clicks$ = fromEvent(document, 'click');
14
15// Custom Observable
16const custom$ = new Observable<number>(subscriber => {
17  subscriber.next(1);
18  subscriber.next(2);
19  setTimeout(() => {
20    subscriber.next(3);
21    subscriber.complete();
22  }, 1000);
23});

Subscription - Listening

1// Full subscription form
2const subscription = numbers$.subscribe({
3  next: value => console.log('Value:', value),
4  error: err => console.error('Error:', err),
5  complete: () => console.log('Completed')
6});
7
8// Short form - only next
9numbers$.subscribe(value => console.log(value));
10
11// Cancelling the subscription
12subscription.unsubscribe();

Naming Convention

In Angular we use the `$` suffix for Observables:

1samurai$: Observable<Samurai[]>;
2loading$: Observable<boolean>;
3error$: Observable<string | null>;
Go to CodeWorlds