-
Notifications
You must be signed in to change notification settings - Fork 0
RxJS Concepts
HaoZhaiX edited this page May 11, 2020
·
1 revision
Observables are lazy Push collections of multiple values. An Observable is a Producer of multiple values, pushing
them to Observers.
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 thatsync
returns a single value on invocation. -
generator
: a lazily evaluated computation thatsync
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 cansync
orasync
return zero to (potentially) infinite values from the time it's invoked onwards.
- 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
orasynchronously
.
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));