There are two different protocols to define the relationship between Producer and Consumer. These protocols are PULL and PUSH.

  • What is Pull? In Pull systems, the Consumer determines when it receives data from the data Producer. The Producer itself is unaware of when the data will be delivered to the Consumer.
  • What is Push? In Push systems, the Producer determines when to send data to the Consumer. The Consumer is unaware of when it will receive that data.

Some ways to manipulate the stream of data using those protocols are:

  • Ajax: works as a pull and not applicable to push data.
  • Promise: is as a Push and can retrieve results once. A Promise (the Producer) delivers a resolved value to registered callbacks (the Consumers). It was very used for AngularJS to asynchronous events.
  • Observable: is a Producer of multiple values, pushing them to Observers (Consumers).

Observables vs Promises

The use of these resources makes attend the use of reactive programming pattern. However, the Observable over-place the use of Promise. Here is some differences between both solutions.

Observable Promise
start with subscription call execute with the creation
many values one value
more then one clauses only one (then)
the subscribe method handling errors the child is responsible for the errors

The different types of observables

An Observable is a stream of asynchronous events that can be processed with array-like operators.[1]. Therefore, Observable is an way to handle asynchronous tasks. It is the resource to manage the reaction of the system. The new version of Angular use the observable and his specialization.

  • Observable
    • Cold: the code is executed even only one observer.
    • Uni-directional: Observer can not assign value to observable.
    • The code will run for each observer.
    • Unicast: emit values from the observable not from any other component.
    • It creates copy of data for each observer.
    • Passive: Observables are passive subscribers to the events
    • Each subscribers get different instance of the event, then the result on each Observer can be different.
    • Lifecycle: creation, subscription, execution and destruction
  • Subject
    • Subject extends Observable
    • Hot: the code is executed and value gets broadcast even if there is no observer.
    • bi-directional: Observer can assign value to observable.
    • Same data is shared between all observers.
    • Active: Subjects can trigger new events using next or complete methods
    • All subscribers get the same event
    • It allows values to be multicasted to many Observers.
    • It can act as both subscribers and emmitter
  • BehaviorSubject
    • BehaviorSubject extends Subject
    • It stores the latest value emitted to its consumers, and whenever a new Observer subscribes, it will immediately receive the "current value"
  • ReplaySubject
    • ReplaySubject extends Subject
    • The subject will miss all the values that are broadcast before creation of observer. A ReplaySubject records multiple values from the Observable execution and replays them to new subscribers.

Using it

The observables are used, for instance, to listen router/forms or handle http request/response of the system and do some operation when a scenario happen. When the observable is part of the framework, the angular handle the observable. However, if the observable is created by the developer then it should be handled and destroyed.

Examples of data sources candidates do be observable: (User Input) Event, Http requests, Triggered in code.

In Angular, the RxJS is the library used to work with asynchronous data streams. It implement the Observable type.

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

This library offer functions to create new Observables. Also, some operators are prepared to react and return a observation like map, filter. Here a dynamic way to compare the operators.

The naming conventions for observables is use the "$".

Below is shown an example of the imports:

import { interval, Subscription, Observable } from 'rxjs';
import { map, filter } from 'rxjs/operators';

Now an example the the observable on router using params:

this.route.params.subscribe((params: Params) => {
    this.id = +params.id;
});

And an example using the method “interval”:

setInterval(() => {
    observer.next(count);
    if (count === 5) {
        observer.complete();
    }
    count++;
}, 1000);

Here is an example using Subject.

private mySubject$: Subject<MyObjectRest> = new BehaviorSubject(null);

ngInit() {
  this.load().pipe(
      switchMap(myObject=> {
        return myObject;
      })
    );
}

load(): Observable<MyObjectRest> {
   return this.getMyObject().pipe(
      tap(
        (value: MyObjectRest) => this.mySubject$.next(value))
      );
}

getMyObject(): Observable<MyObjectRest> {
    return this.http.get<MyObjectRest>("https://myapp/endpoint");
}

References