catalogue
- preface
- Observer mode
- Iterator mode
- Combination and implementation of two modes in RxJS
- Summary
- reference resources
1. Preface
RxJS is a library that uses observable sequences to write asynchronous and event based programs. It combines observer mode, iterator mode and functional programming using sets to manage everything needed for the sequence of events in an ideal way.
This article will mainly discuss the observer pattern, iterator pattern and how they are applied in RxJS.
2. Observer mode
It realizes the logical separation relationship between producer (creator of event) and consumer (listener of event).
The monitoring and triggering of browser DOM events should be the implementation of the most typical observer mode of the Web front end.
document.body.addEventListener('click', function listener(e) { console.log(e); }); document.body.click(); // Simulate user clicks
Listen: Send a message to document.com through addEventListener The body node is bound with an event handler function of click event.
Trigger: when the user clicks the page (body), the body node will trigger the bound event handler.
The diagram is as follows:
3. Iterator mode
Users can access each element in the collection through a specific interface without understanding the underlying implementation.
Starting from ES 6, a new traversal mechanism - iterator is introduced, which is an implementation of iterator pattern in JavaScript. In JavaScript, an iterator is an object that defines a sequence and may return a return value when terminated. More specifically, the iterator is implemented by using the next() method Iterator protocol (iterator protocol), the method returns an object with two attributes: value and done, where value represents the specific return value and done indicates whether the iteration has been completed.
String,Array,Map and Set And so on are built-in iterative objects, and their prototype objects all have one Symbol.iterator method.
const arr = ['a', 'b']; const iterator = arr[Symbol.iterator](); // Get iterator object iterator.next(); // { value: 'a', done: false } iterator.next(); // { value: 'b', done: false } iterator.next(); // { value: undefined, done: true }
We often use for-of Loop through iteratable objects:
const arr = ['a', 'b']; for (let value of arr) { console.log(value); // a b }
For of syntax is to facilitate traversal of iteratable objects, and its internal implementation calls symbol Iterator method, similar to the following code:
const arr = ['a', 'b']; const iterator = arr[Symbol.iterator](); let result = iterator.next(); while (!result.done) { console.log(result.value); // a b result = iterator.next(); }
Iterator features:
- Access the contents of the collection without knowing the underlying implementation.
- It provides a unified interface to traverse different collection structures, so as to support the same algorithm to operate on different collection structures.
4. Combination and implementation of two modes in rxjs
RxJS contains two basic concepts: * * Observable * * and Observer.
Observable, as an observable object (observable), is a collection of callable future values or events (asynchronous or synchronous data flow).
As an Observer, Observer is a collection of callback functions. It knows how to listen to the value provided by Observable.
The subscription publication relationship (Observer mode) between Observable and Observer is as follows:
Subscription: Observer subscribes to Observable through the subscribe() method provided by Observable.
Publish: Observable publishes events to Observer through the next method provided by Observer.
The pseudo code of the relationship between the two is as follows:
// Observer const observer = { next(value) { console.log(value); } }; // Observable function Observable (observer) { setTimeout(()=>{ observer.next('A'); }, 1000); } // subscribe Observable(observer);
It can be seen from the above that the so-called subscription is to inject the Observer observer into the Observable object Observable.
In RxJS, in addition to the next method to receive Observable events, Observer also provides two other methods: error() and complete() to handle exceptions and completion status.
const observer = { next(value) { /* Processing value */ }, error(err) { /* Handling exceptions */ }, complete() { /* State processing completed */ } };
Combine Iterator with Iterator to understand the three methods of Observer:
- next(): Observer accepts Observable streams (collections) by providing the next method, which is a push form (push).
- Compared with Iterator, it is through calling Iterator Next () takes the value, which is in the form of pull.
- complete(): when no new value is issued, the complete method of Observer will be triggered.
- Compared with Iterator, when done in the return result of next() is true, it means complete.
- error(): when an exception occurs in the processing of an event, the exception is caught through try catch, and the Observer provides the error method to receive the error for unified processing.
A simple RxJS subscription publish instance:
import { Observable } from 'rxjs'; const observable = new Observable(function (observer) { // Notify the observer observer.next('a'); observer.next('b'); observer.complete(); // This observer will be unsubscribed // observer.error(new Error('err')); observer.next('c'); // Since it has been complete d, it will not be sent again }); // Define the observer, and the next, complete and error methods handle different states of the flow const observer = { next: (value) => console.log(value), error: err => console.error('Observer got an error: ' + err), complete: () => console.log('Observer got a complete notification') } // Subscribe to Observable and execute const subscription = observable.subscribe(observer); // A cancelable subscription object subscription will be returned
Execution result:
a b
5. Summary
One sentence overview of the Observer + iterator mode implemented in RxJS: inject the Observer observer into the Observable object Observable, and then process the different states of the flow in the Observable object Observable by calling the next, complete and error methods provided by the Observer, so as to realize a sequential access processing of the data flow.