10 minute learns

Reactive JavaScript: Observables

What

  • A new-ish way to deal with asynchronous JavaScript
  • Similar concept to streams (Java) or pipes (Unix)
  • Like a Promise...but more powerful

Why

  • Web Apps are becoming increasingly complex
  • Observables deal with 0, 1 or n events
  • Powerful with websockets
  • Not only for subscribing to API's
  • Great for passing messages between components (declarative + decoupling approach)
  • Better customer experience

How

Example 1: Observables vs. Promises

import {Observable, Observer} from 'rxjs';

export class TodoService {
    public listPromise() {
        return new Promise((accept, reject) => {
            fetch('example.com/api/things').then(
                value => accept(value),
                error => reject(error)
            )
        })
    }
    public listObservable() {
        return new Observable((observer: Observer) => {
            fetch('example.com/api/things').then(
                value => observer.next(value),
                error => observer.error(error)
            )
        })
    }
}

const todoService = new TodoService();

todoService.listPromise().then(
    value => console.log(value),
    error => console.error(error)
);

todoService.listObservable().subscribe(
    value => console.log(value),
    error => console.error(error)
);

Example 2: Pipes

import {filter, finalize, map} from "rxjs/operators";
import {Observable, of} from "rxjs";

let isLoading = true;

// creates an observable with return value of `[1, 2, 3]`
of([1, 2, 3])
    .pipe(
        // increases each index by 1 => [2, 3, 4]
        map(x => x + 1),

        // filters out any value that is > 2 => [2]
        filter(x => x > 2),

        // stops loading after the obs is finished
        finalize(() => isLoading = false)
    )
    .subscribe(
        value => value,
        error => console.error(error)
    );

Example 3: Streams (Intervals)

import {interval} from 'rxjs';
import {sample} from 'rxjs/operators';

// emit value every 1s
const source = interval(1000);

// sample last emitted value from source every 2s
const example = source.pipe(sample(interval(2000)));

// output: 2..4..6..8..
const subscribe = example.subscribe(val => console.log(val));

Example 4: Other things to observe

import {fromEvent, merge} from 'rxjs';
import {sample, mapTo} from 'rxjs/operators';

const listener = merge(
    fromEvent(document, 'mousedown').pipe(mapTo(false)),
    fromEvent(document, 'mousemove').pipe(mapTo(true))
)
    .pipe(sample(fromEvent(document, 'mouseup')))
    .subscribe(isDragging => {
        console.log('Were you dragging?', isDragging);
    });

Reactive JavaScript: Observables

By Matt Rowles

Reactive JavaScript: Observables

A quick introduction into Reactive JavaScript and using Observables to power your app.

  • 50