当前位置:网站首页>Rxjs TakeUntil 操作符的学习笔记
Rxjs TakeUntil 操作符的学习笔记
2022-06-25 15:39:00 【汪子熙】
TakeUntil 的官方文档对这个操作符的解释是:
Emit values until provided observable emits.
即它可以被赋予另一个起锚定作用的 Observable,当该锚定 Observable emit 值时,原始的 Observable 就停止发射值,进入 complete 操作。
看一个实际的例子:
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 每个1秒的时间间隔,发射一个从 0 开始递增间隔为 1 的整数序列。
我们构造了一个 timer Observable,超时时间间隔为 5 秒,也就是说,在第五秒时,该 Observable 会发送一个值。这个 timer Observable 传入 takeUntil,作为一个 notification Observable,五秒钟之后,source Observable 就会停止发射整数。
最后上述程序执行的输出:4 秒之内打印 0~4,然后结束。

另一个例子:
const interval = interval(1000);
const clicks = fromEvent(document, 'click');
const result = interval.pipe(takeUntil(clicks));
result.subscribe(x => console.log(x));
这个例子里,interval 作为原始的 Observable,clicks 作为 notification Observable,整个程序的表现形式是,每个 1 秒有一个递增1的整数序列打印,直至页面发生点击事件时,原始 interval Observable 终止。
看另一个例子:
// 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));
我们逐行分析这个例子的逻辑:
const evenSource = source.pipe(filter(isEven));
产生一个每隔1秒发射一个偶数的 Observable.
const evenNumberCount = evenSource.pipe(scan((acc, _) => acc + 1, 0));
对产生的偶数的个数进行累加。
const fiveEvenNumbers = evenNumberCount.pipe(filter(val => val > 5));
当产生的偶数个数大于 5 时,发射值。这个 Observable 作为 takeUntil 的 notification Observable 使用。
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)
);
- 使用 eventSource 和 eventNumberCount,通过
withLatestFrom将两个 Observable 进行连接,从而在 map Operator 里,可以同时打印出当前发射的偶数值和偶数总量。通过 takeUntil 传入一个只有在偶数总数个数大于 5 时才发射值的 Observable,可以做到偶数总数大于 5 之后,让 interval 停止值的发送。
最后的执行效果:

边栏推荐
- Power representation in go language
- B站付费视频使up主掉粉过万
- 加载本地cifar10 数据集
- JVM memory region details
- Golang uses Mongo driver operation - increase (Advanced)
- Describe your understanding of the evolution process and internal structure of the method area
- Go development team technical leader Russ Cox sends a document to share go's version control history
- Most commonly used SQL statements
- appium服务的启动与关闭踩坑记录
- MySQL installation tutorial
猜你喜欢

Sword finger offer 07 Rebuild binary tree
Client development (electron) system level API usage

剑指 Offer 04. 二维数组中的查找

教务系统开发(PHP+MySQL)

异步处理容易出错的点

不要再「外包」AI 模型了!最新研究发现:有些破坏机器学习模型安全的「后门」无法被检测到
Take you to the open source project of smart home: the preliminary configuration of zhiting home cloud and home assistant+ homebridge

MySQL transaction characteristics and implementation principle
Time wheel and implementation analysis of time wheel in go zero

地理位置数据存储方案——Redis GEO
随机推荐
Deep learning pytorch cifar10 dataset training "suggestions collection"
Pytest test framework notes
Golang regular regexp package uses -05- extend expand(), cut split() according to the rule
Analysis of the concept of metacosmic system
Introduction to MgO 256gb NAND flash chip
TensorFlow加载cifar10数据集
说下你对方法区演变过程和内部结构的理解
Mixed density network (MDN) for multiple regression explanation and code example
Optimization of lazyagg query rewriting in parsing data warehouse
Download and installation tutorial of consumer
Take you to the open source project of smart home: the preliminary configuration of zhiting home cloud and home assistant+ homebridge
教务系统开发(PHP+MySQL)
JS的遍历和分支判断(2022年6月24日案例)
分享自己平时使用的socket多客户端通信的代码技术点和软件使用
Mapbox map - inconsistent coordinate system when docking GIS layers?
MT60B1G16HC-48B:A美光内存颗粒FBGA代码D8BNK[通俗易懂]
Based on neural tag search, the multilingual abstracts of zero samples of Chinese Academy of Sciences and Microsoft Asiatic research were selected into ACL 2022
Gold three silver four, an article to solve the resume and interview
What are the reasons why the game industry needs high defense servers?
Lecun predicts AgI: big model and reinforcement learning are both ramps! My "world model" is the new way