Learn RxJS (02) : Introduces RxJS and Observables

The last article gave you a general explanation of what is responsive programming, this article we will understand RxJS, RxJS is a specific implementation of responsive programming; There are other libraries that also implement responsive programming, such as Cyc.js, bacon.js, most. Why should we study RxJS and not those other libraries? The main reasons are as follows:

Being a Producer of data A Consumer of data
Pull passive: Data is produced when consumers request it active: Decide when you need data
Push active: Produce data at your own pace passive: Receives data and reacts

In JavaScript, the Pull types are Function and Iterator, where Function can return only one result at a time, while Generator(which complies with both the iterable and Iterator protocols) can return multiple results at a time. There are promises of Push type. Promises can return one result asynchronously, but not multiple results asynchronously. So in RxJS, there is an Observable that can return multiple results synchronously or asynchronously, which is equivalent to adding a condition that can return multiple values in Push mode. We can also use the following table to represent the above:

SINGLE(returns a SINGLE value) MULTIPLE(return MULTIPLE values)
Pull Function Iterator
Push Promise Observable

One more thing to note: Functions, iterators, and Observables are all deferred, that is, functions only perform operations when called and iterators only perform operations when iterated. An Observable only performs an operation when it’s subscribed. Let’s start by creating an Observable and subscribing to it; The code is as follows:

import { Observable } from "rxjs";

const observable = Observable.create(observer => {
  observer.next(1);
  observer.next(2);
  setTimeout(() => {
    observer.next(3);
  }, 100);
});

console.log("before subscribe");
const subscription = observable.subscribe(val => {
  console.log(`val: ${val}`);
});
console.log("after subscribe");Copy the code

The console output is as follows:

before subscribe
val: 1
val: 2
after subscribe
val: 3Copy the code

From the console results, we can see that the Observable we created synchronously sends 1 and 2 after subscribing, and then sends 3 after 100ms. And we added extra code before and after the Observable subscription to see how the Observable sends its values. Observables can send values asynchronously as well as synchronously. This article gives a brief introduction to RxJS and Observables. In the next article, we will take a closer look at Observables.

Reference: Observable

Copyright Notice: Share – Keep attribution – Non-commercial use – No deduction