search
HomeWeb Front-endJS TutorialDetailed explanation of rxjs

Detailed explanation of rxjs

Mar 13, 2018 pm 04:31 PM
javascriptrxjsDetailed explanation

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft