This time I will bring you a detailed explanation of rxjs, what are the precautions when using rxjs, the following is a practical case, let's take a look.
rxjs (Reactive Extensions for JavaScript) is a responsive extension of JavaScript. The responsive idea is to convert data, status, events, etc. that change over time into an observable sequence. (Observable Sequence), and then subscribes to the changes in the objects in the sequence. Once it changes, various pre-arranged transformations and operations will be performed.
rxjs is suitable for asynchronous scenarios and can be used to optimize requests and events in front-end interactions.
rxjs Features
Unify the specifications of asynchronous programming. Whether it is Promise, ajax or events, they are all encapsulated into sequences (Observable Sequence). Once an asynchronous link changes, you can intercept it by observing the sequence. Changed information.
The front-end business layer and the presentation layer are decoupled. For example, the presentation layer does not need to care about the processing logic that has nothing to do with the DOM when a specified event is triggered. At the same time, the business layer can also assemble the relationship between multiple asynchronous logic in asynchronous operations without exposing it to the presentation layer. The presentation layer is concerned about: data changes in the asynchronous operation.
rxjs development business layer has the characteristics of high elasticity, high stability, and high real-time performance.
rxjs instance concept
Observable: Observable data sequence.
Observer: Observer instance, decides when to observe the specified data.
Subscription: Observing the data sequence returns the subscription instance.
Operators: Observable operation methods, including converting data sequences, filtering, etc. The parameters accepted by all Operators methods are the values of the last data change sent, and the method return value is called To emit new data changes.
Subject: Observed object.
Schedulers: Control scheduling concurrency, that is, when the Observable accepts the Subject's change response, the response method can be set through the scheduler. Currently, the built-in The response can be viewed by calling Object.keys(Rx.Subject).
Observable has four life cycles: creation, subscription, execution, and destruction.
Create an Obervable and return the observed sequence source instance. This instance does not have the ability to send data. In contrast, the observation object instance created through new Rx.Subject has the ability to send the data source.
You can subscribe to the response method (callback method) when the sequence emits new data changes through the sequence source instance.
The response action is actually the execution of Observable.
The sequence source instance can be destroyed, and will be automatically destroyed when an error occurs in the subscription method.
The catch method of the sequence source instance can capture errors that occur in the subscription method, and the sequence source instance can accept the value returned from the catch method as a new sequence source instance.
rxjs operators
rxjs provides many operators for creating Observable objects
import Rx from 'rxjs';
create
let observable = Rx.Observable .create((observer)=> { observer.next('hello'); observer.next('world'); }); //订阅Observable observable.subscribe((value)=> { console.log(value); });
Output: hello
world
of
Convert value variable
let observable = Rx.Observable.of('hello', 'world'); observable.subscribe({ next: (value)=> { console.log(value); }, complete: ()=> { console.log('complete'); }, error: (error)=> { console.log(error); } });
Output: hello
world
complete
from
Convert array variable
let array = [1, 2, 3];let observable = Rx.Observable.from(array); observable.subscribe({ next: (value)=> { console.log(value); }, complete: ()=> { console.log('complete'); }, error: (error)=> { console.log(error); } });
Output: 1
2 3 complete fromEvent
Convert event variable
Rx.Observable.fromEvent(document.querySelector('button'), 'click'); fromPromise
Convert Promise (promise) variable
let observable = Rx.Observable .fromPromise(new Promise((resolve, reject) => { setTimeout(() => { resolve('hello world'); },3000) })); observable.subscribe({ next: (value)=> { console.log(value); }, complete: ()=> { console.log('complete'); }, error: (error)=> { console.log(error); } });
Output: hello world
complete
empty
The empty operator returns an empty Observable, subscribe to the object , it will return complete information immediately.
never
The never operator will return an infinite Observable. If you subscribe to the object, nothing will happen. It is an Observable object that always exists but does nothing.
interval
The interval operator supports a parameter of numeric type, which is used to represent the timing interval.
let observable = Rx.Observable.interval(1000); observable.subscribe({ next: (value)=> { console.log(value); }, complete: ()=> { console.log('complete'); }, error: (error)=> { console.log(error); } });
Output: 0
1 2 ...
The above code indicates that every 1s, an increasing value will be output, and the initial value starts from 0.
timer
The timer operator supports two parameters. The first parameter is used to set the waiting time to send the first value. The second parameter indicates that after the first sending, The time between sending other values.
let observable = Rx.Observable.timer(1000, 5000);
observable.subscribe({ next: (value)=> { console.log(value); }, complete: ()=> { console.log('complete'); }, error: (error)=> { console.log(error); } });
Output: 0 //After 1s
1 //After 5s
2 / /5s later
...
Pull vs Push
Pull and Push are two different communication methods between data producers and data consumers
Pull
In the Pull system, the data consumer decides when to obtain data from the data producer, and the producer itself does not realize when the data will be sent to the consumer.
Each JavaScript function is a Pull system. The function is the producer of data. The code that calls the function consumes the data by pulling out a single return value.
Iterator and generator in ES6Generator is another Pull system. The code that calls iterator.next() is a consumer and can pull multiple values from it.
Push
In the Push system, the producer of data decides when to send data to the consumer. The consumer will not realize that it is going to receive the data before receiving the data.
Promise is the most common Push system. A Promise (producer of data) sends a resolved (success status) or reject (failure status) to execute a callback (data consumer), but it is different from a function in that : Promise determines when data is pushed to this callback function.
RxJS introduces Observables (observable objects), a new Push system. An observable object is a producer that generates multiple values. When new data is generated, it will be actively pushed to the Observer.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
SVG animation in front-end development
TypeScript you must understand
The above is the detailed content of Detailed explanation of rxjs. For more information, please follow other related articles on the PHP Chinese website!