Home Web Front-end JS Tutorial Detailed explanation of rxjs

Detailed explanation of rxjs

Mar 13, 2018 pm 04:31 PM
javascript rxjs Detailed 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);
});
Copy after login

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);
    }
});
Copy after login

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);
    }
});
Copy after login

Output: 1

    2     3     complete
fromEvent
Copy after login

Convert event variable

Rx.Observable.fromEvent(document.querySelector('button'), 'click');
fromPromise
Copy after login

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);
    }
});
Copy after login

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);
    }
});
Copy after login

Output: 0

    1
     2
     ...
Copy after login

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);
    }
});
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Detailed explanation of numpy version query method Detailed explanation of numpy version query method Jan 19, 2024 am 08:20 AM

Numpy is a Python scientific computing library that provides a wealth of array operation functions and tools. When upgrading the Numpy version, you need to query the current version to ensure compatibility. This article will introduce the method of Numpy version query in detail and provide specific code examples. Method 1: Use Python code to query the Numpy version. You can easily query the Numpy version using Python code. The following is the implementation method and sample code: importnumpyasnpprint(np

See all articles