Rxjs

Creating observable

See Observable

import { Observable } from 'rxjs'

const observable = new Observable((subscriber) => {
    const id = setInterval(() => { 
        subscriber.next("hi");
    }, 1000);
})

Creating observer

Observer is to subscribe to this, we can do

observable.subscribe((value) => console.log(value));

The value of hi will then be populated into this function;

To stop publishing, observable can then call .complete(). For example:

import { Observable } from 'rxjs'

const observable = new Observable((subscriber) => {
    const id = setInterval(() => { 
        subscriber.next("hi");
        subscriber.complete();
    }, 1000);
})

Because of this, the client only see hi and stop.

The observer itself can also be expanded as an object


const observer: Observer<number> = {
  next(x: number) {
    console.log(x);
  },
  error(err: string) {
    console.error(err);
  },
  complete() {
    console.log("done");
  }
}

observable.subscribe(observer)

Without this, we just simply call next

Subscription

Output of .subscribe is Subscription.

import { Observable, type Observer } from "rxjs";

const observable = new Observable<number>((client) => {
  setInterval(() => {
    client.next(1);
  }, 1000)
})


const subscription = observable.subscribe((x) => console.log("receive " + x));

setTimeout(() => subscription.unsubscribe(), 5000);

This allows us to unsubscribe and stuff.

To clear interval, we can do something like this

import { Observable } from "rxjs";

const observable = new Observable<number>((client) => {
  const id = setInterval(() => {
    client.next(1);
  }, 1000);

  return () => {
    console.log("clear interval")
    clearInterval(id);
  }
})


const subscription = observable.subscribe((x) => console.log("receive " + x));

setTimeout(() => subscription.unsubscribe(), 5000);

the return function of observable is auto-called by rxjs.

Operation

Piping

pipe take 1 observable and return another observable and leave the original observable alone. Normally is used for transforming.

For example:

import { of, first, map } from "rxjs";
of(1, 2, 3, 4).pipe(map((x) => x * 2), first()).subscribe((x) => console.log(x));

of create a new observable, we then feed this into map function. The syntax pipe(op1, op2) is similar to op2(op1()) so the output of map() goes to the input of first.

Creation operator

import { interval } from 'rxjs';

const observable = interval(1000 /* number of milliseconds */);

This is for creating an observer.

High-order Observables

We can have nested stream one stream goes into another stream

import { of, first, map, concatAll, mergeAll, take, interval, switchAll, exhaustAll } from "rxjs";

const inner = (name: string) => interval(1000).pipe(take(3), map((i) => `${name}${i}`));

const outer$ = interval(1600).pipe(take(3), map((i) => inner("abc"[i])))

// concatAll = sequential so outer first and then inner, so a0,a1,a2 and b0 b1 b2
// mergeAll = run all at once, emit whichever arrive first
// switchAll = latest win
// exhaustAll = ignore repeat trigger if we still processing

outer$.pipe(exhaustAll()).subscribe(console.log)
OperatorBehaviorWhat happens to bOutput
concatAllQueue: one inner at a time, in orderWaits until a completesa0 a1 a2 b0 b1 b2 c0 c1 c2
mergeAllRun all at once, emit values as they arrive (interleaved)Starts immediatelya0 a1 b0 a2 b1 c0 b2 c1 c2
switchAllLatest wins: a new inner cancels the previous oneCancels a, then gets cancelled by ca0 b0 c0 c1 c2
exhaustAllIgnore new inners while one is still runningDropped, never runsa0 a1 a2 c0 c1 c2

Use cases:

OperatorTypical use
concatAllOrder matters, e.g. saving edits one after another
mergeAllIndependent parallel work, e.g. loading many images
switchAllOnly the latest matters, e.g. search-as-you-type
exhaustAllIgnore repeat triggers, e.g. a submit button clicked many times