当前位置:网站首页>Learning notes of rxjs takeuntil operator
Learning notes of rxjs takeuntil operator
2022-06-25 16:04:00 【WangZiXi】
TakeUntil The official documentation for this operator is :
Emit values until provided observable emits.
That is, it can be given another anchoring role Observable, When the anchor Observable emit When the value of , The original Observable Just stop firing , Get into complete operation .
Look at a practical example :
import {
interval, timer } from 'rxjs';
import {
takeUntil } from 'rxjs/operators';
//emit value every 1s
const source = interval(1000);
//after 5 seconds, emit value
const timer$ = timer(5000);
//when timer emits after 5s, complete source
const example = source.pipe(takeUntil(timer$));
//output: 0,1,2,3
const subscribe = example.subscribe(val => console.log(val));
source Observable Every 1 Second time interval , Launch one from 0 The start increment interval is 1 Integer sequence of .
We constructed a timer Observable, The timeout interval is 5 second , in other words , At the fifth second , The Observable Will send a value . This timer Observable Pass in takeUntil, As a notification Observable, Five seconds later ,source Observable Will stop firing integers .
Finally, the output of the above program execution :4 Print in seconds 0~4, Then the end .
Another example :
const interval = interval(1000);
const clicks = fromEvent(document, 'click');
const result = interval.pipe(takeUntil(clicks));
result.subscribe(x => console.log(x));
In this case ,interval As a primitive Observable,clicks As notification Observable, The expression of the whole program is , Every 1 The second has an increment 1 Integer sequence printing , Until a click event occurs on the page , original interval Observable End .
Look at another example :
// RxJS v6+
import {
interval } from 'rxjs/observable/interval';
import {
takeUntil, filter, scan, map, withLatestFrom } from 'rxjs/operators';
//emit value every 1s
const source = interval(1000);
//is number even?
const isEven = val => val % 2 === 0;
//only allow values that are even
const evenSource = source.pipe(filter(isEven));
//keep a running total of the number of even numbers out
const evenNumberCount = evenSource.pipe(scan((acc, _) => acc + 1, 0));
//do not emit until 5 even numbers have been emitted
const fiveEvenNumbers = evenNumberCount.pipe(filter(val => val > 5));
const example = evenSource.pipe(
//also give me the current even number count for display
withLatestFrom(evenNumberCount),
map(([val, count]) => `Even number (${
count}) : ${
val}`),
//when five even numbers have been emitted, complete source observable
takeUntil(fiveEvenNumbers)
);
/* Even number (1) : 0, Even number (2) : 2 Even number (3) : 4 Even number (4) : 6 Even number (5) : 8 */
const subscribe = example.subscribe(val => console.log(val));
Let's analyze the logic of this example line by line :
const evenSource = source.pipe(filter(isEven));
Generate an interval 1 An even number of seconds Observable.
const evenNumberCount = evenSource.pipe(scan((acc, _) => acc + 1, 0));
Accumulate the number of even numbers generated .
const fiveEvenNumbers = evenNumberCount.pipe(filter(val => val > 5));
When the number of even numbers generated is greater than 5 when , Emission value . This Observable As takeUntil Of notification Observable Use .
const example = evenSource.pipe(
//also give me the current even number count for display
withLatestFrom(evenNumberCount),
map(([val, count]) => `Even number (${
count}) : ${
val}`),
//when five even numbers have been emitted, complete source observable
takeUntil(fiveEvenNumbers)
);
- Use eventSource and eventNumberCount, adopt
withLatestFrom
Put two Observable Connect , Thus in map Operator in , You can print the even value and even total amount of the current emission at the same time . adopt takeUntil Pass in one only if the total number of even numbers is greater than 5 When the value is emitted Observable, The total number of even numbers can be greater than 5 after , Give Way interval Stop sending values .
The final execution effect :
边栏推荐
- Once the code was encrypted by the company's computer, the compilation failed
- Lecun predicts AgI: big model and reinforcement learning are both ramps! My "world model" is the new way
- f_read 函数[通俗易懂]
- 普通人的2022春招总结(阿里、腾讯offer)
- Report on Hezhou air32f103cbt6 development board
- Do you want to go to an outsourcing company? This article will give you a comprehensive understanding of outsourcing pits!
- 原生js动态添加元素
- What is OA
- Interviewer: your resume says you are proficient in mysql, so you say cluster / Union / overlay index, table return, index push down
- Asynchronous processing of error prone points
猜你喜欢
Practice of geospatial data in Nepal graph
Rapport de la main - d'oeuvre du Conseil de développement de l'aecg air32f103cbt6
Do you want to go to an outsourcing company? This article will give you a comprehensive understanding of outsourcing pits!
Asynchronous processing of error prone points
商城风格也可以很多变,DIY 了解一下!
Sword finger offer II 091 Paint the house
iVX低代码平台系列详解 -- 概述篇(一)
Lifeifei's team applied vit to the robot, increased the maximum speed of planning reasoning by 512 times, and also cued hekaiming's MAE
说下你对方法区演变过程和内部结构的理解
Super comprehensive custom deep copy function
随机推荐
MySQL installation tutorial
Golang uses Mongo driver operation - increase (Advanced)
VectorDraw Developer Framework 10.1001 Crack
Activation and value transfer of activity
Uncover gaussdb (for redis): comprehensive comparison of CODIS
GO语言-什么是临界资源安全问题?
The database records are read through the system time under the Android system, causing the problem of incomplete Reading Records!
Analysis of the concept of metacosmic system
JS的注释
镁光256Gb NAND Flash芯片介绍
Introduction to database transactions
商城风格也可以很多变,DIY 了解一下!
不要小看了积分商城,它的作用可以很大!
元宇宙系统的概念解析
Yadali brick playing game based on deep Q-learning
Stop "outsourcing" Ai models! The latest research finds that some "back doors" that undermine the security of machine learning models cannot be detected
Share the code technology points and software usage of socket multi client communication
MT60B1G16HC-48B:A美光内存颗粒FBGA代码D8BNK[通俗易懂]
AspNetCore&云效Flow持续集成
Multithreading, parallelism, concurrency, thread safety