RxJS profile
RxJS is based on the observer pattern and iterator pattern with functional programming thinking. To put it simply, RxJS is an interactive process of data production and consumption between Observables and observers. Therefore, understanding RxJs requires a deep understanding of Observables and Observers. As the name implies, an Observable is an Observable, and an Observer is an Observer. The two observables are connected by the Sunscribe method on an Observable as a bridge. The data flow of RxJS is an Observable, which implements two design patterns, Observer Pattern and Iterator Pattern.
Observer model
The Observer Pattern defines
The observer pattern is one of the software design patterns. In this mode, a target object manages all observer objects that depend on it and actively notifies itself of changes in its state. This is usually done by calling the methods provided by each observer. This mode is commonly used in real-time event processing systems. —- Wikipedia
The observer pattern can be used when there is a one-to-many relationship between objects, such as notifying and updating multiple objects when an object is updated. The publisher publishes the notification, and the observer receives the notification and performs the update. The observer model is a behavioral model. In RxJS, an Observable is a publisher and Observer, and the two are related by subscribing.
import { of } from 'rxjs';
const source$ = of(1[2]);
source$.subscribe(console.log);
Copy the code
The observer model is the idea of divide and conquer. The idea is to separate the problem of replication, and each part has its own functional module to handle it. In RxJS, it basically breaks down a complex problem into three small problems:
- How events are generated is the responsibility of the publisher, which in RxJS is the job of the Observable.
- How to respond to events, which is the responsibility of the observer, is determined by the argument subscribe in RxJS.
- How publishers are associated with observers, that is, when subscribe is called. Thus the Observer pattern of thinking, logic is divided into a Publisher (Publisher) and the Observer (the Observer), the Publisher responsible for generating the event, and to generate data to inform all registered observers, and don’t care about how to deal with these events, the Observer, the Observer can be registered to a Publisher, The event is received and processed, regardless of how the data was generated. The benefits of the observer model are obvious. Both parties in this model can focus on one thing and can be combined in any way.
Iterator pattern
The Iterator Pattern definition
In object-oriented programming, the iterator pattern is one of the simplest and most common design patterns. It allows users to tour each element in a container through a specific interface without knowing the underlying implementation. It is also possible to implement purpose-specific versions of iterators. —- Wikipedia
Iterator pattern, also known as Cursor pattern. Provides a generic interface for traversing a data set without the need for an internal implementation of the relational data set. Like a moving pointer, it moves from one element to another, completing a walk through the collection.
const array = [1.2.3];
const iterator = array[Symbol.iterator]();
iterator.next(); // {value: 1, done: false}
Copy the code
In ES6, iterator mode:
- The next method moves the cursor to the next element
- The value property gets the current value
- RxJS, as the user of the iterator, doesn’t need to take the initiative to “pull” the generated data from the Observable for consumption. It just needs to subscribe to the Observable. Messages are naturally pushed, which is the advantage of combining the observer and iterator patterns.
Create observables
Creating an Observable is easy enough, and RxJS provides a number of class creation operators.
import { interval } from 'rxjs';
const source$ = interval(1000);
source$.subscribe(console.log);
Copy the code
Observable calls observer next to pass data. It can actually pass an observer in a Subscribe bridge method like {next(){}, complete(){}, error(){}}, Data, end state, and errors are processed by the Observable. You can also pass three function arguments separately. It should be noted that an Observable has only one terminal state, complete or error. Once it enters the error state, the Observable terminates and does not call the next function corresponding to the Observer. The Observer complete function is no longer called; Likewise, Observer next and error can no longer be called if an Observable enters a finished state.
Unsubscribe observables
Observables and observers are initially connected by subscribe, and sometimes they need to be disconnected under certain conditions. In RxJS, the subscribe function returns the Subscription object. Calling the unsubscribe function on the Subscription unsubscribe allows you to unsubscribe an Observable.
import { interval } from 'rxjs';
const source$ = interval(1000);
const subscription = source$.subscribe(console.log);
setTimeout((a)= > subscription.unsubscribe(), 3000); // Unsubscribe after 3 seconds
Copy the code
hot & cold
Think of a hot Observable as a radio station. All of the listeners that are listening to it at this moment listen to the same song.A cold Observable is a music CD. Many people can buy it and listen to it independently.by Nickolay Tsvetinov
An Observable is a data stream that can produce a series of data in a time frame. Simple scenarios with only one Observer don’t need much consideration, but complex scenarios with multiple observers, especially if multiple observers don’t subscribe at the same time. There are two things that need to be considered to pass appropriately generated data to the Observer. There are two options:
- A: A Cold Observable. You can’t miss it. You need to get all the data generated by the Observable.
- B: Hot Observable, which can be missed, gets the start time of the subscription counting all data generated by the Observable.
Hot Observables keep happening and generating data whether they are subscribed or not. When a Hot Observable has multiple subscribers, it shares information with each subscriber in a one-to-many relationship. A Cold Observable doesn’t start executing the code that streams data until it’s subscribed. And a Cold Observable has a one-to-one relationship with subscribers. When there are multiple different subscribers, messages are sent in full. In other words, for a Cold Observable, when there are multiple subscribers, their events are independent. Different scenarios can have different expectations about whether to use a Hot Observable or a Cold Observable. RxJS provides both of these requirements scenarios. It also provides switching between hot and cold.