Skip to content

RxJS Concepts

HaoZhaiX edited this page May 11, 2020 · 1 revision

Observable

Observables are lazy Push collections of multiple values. An Observable is a Producer of multiple values, pushing them to Observers.

1. Pull vs Push

Pull and Push are two different protocols that describe how a data Producer can communicate with a data Consumer.

  • Pull : In Pull systems, the Consumer determines when receives data and the Producer is unaware of when data will be delivered. (Function, Iterator)

  • Push : In Push systems, the Producer determines when to send data, and the Consumers is unaware of when it will receive the data. (Promise, Observable)

Different implementations for pull and push protocols:

  • Function: a lazily evaluated computation that sync returns a single value on invocation.
  • generator: a lazily evaluated computation that sync returns zero to (potentially) infinite values on iteration.
  • Promise: a computation that may (or may not) eventually return a single value.
  • Observable: a lazily evaluated computation that can sync or async return zero to (potentially) infinite values from the time it's invoked onwards.

2. Observable as generalizations of functions

  • Observables are like functions with zero arguments, but generalize those to allow multiple values.
  • Subscribing to an Observable is analogous to calling a Function.
  • Observables are able to deliver values either synchronously or asynchronously.
import { Observable } from 'rxjs'

// Create an Observable that pushes the values 1, 2, 3 immediately (synchronously) 
// when subscribed, and the value 4 after one second has passed
const foo = new Observable(subscriber => {
    subscriber.next(1);
    subscriber.next(2);
    subscriber.next(3);

    // async output
    setTimeout(() => {
        subscriber.next(4);
    }, 1000);
);

// Need to subscribe to invoke the Observable and see these values
foo.subscribe(x => console.log(x));

Operators

Subscription

Subjects

Scheduler

Reference