当前位置:网站首页>rxjs Observable filter Operator 的实现原理介绍
rxjs Observable filter Operator 的实现原理介绍
2022-07-03 12:34:00 【汪子熙】
看下面这段使用 filter Operator 的代码:
import {
fromEvent, interval, MonoTypeOperatorFunction } from 'rxjs';
import {
filter } from 'rxjs/operators';
function filterKey(key) {
console.log('input: ', key);
const result: MonoTypeOperatorFunction<KeyboardEvent> = filter(
(event: KeyboardEvent) => {
console.log('input event: ', event);
return event.key === key;
}
);
console.log('result: ', result);
return result;
}
fromEvent(document, 'keyup')
.pipe(filterKey('Enter'))
.subscribe(
(data) => console.log(data) // KeyboardEvent
);
原始 Observable 调用 pipe,执行自定义 Operator 的逻辑,在逻辑里生成一个 filter Operator 实例。单步调试如下:

返回一个 filterOperatorFunction:

filter 调用返回的是一个 filterOperatorFunction:
至此我们只完成了 pipe 两段调用的第一段:得到 filter 返回的 filterOperatorFunction.

然后执行 pipe 操作的第二段,如上图图例所示,将原始 Observable 传入 filterOperatorFunction:

这个第二段操作,就会创建新的 FilterOperator 实例,在 lift 操作里,新建一个 Observable,然后把原始的 Observable 设置为这个新 Observable 实例的 source 字段,将 FilterOperator 实例赋给原始 Observable 的 Operator 字段。
pipe 调用执行的结果,返回一个新的 Observable 给 pipe 的调用者。最后我们 subscribe 的,就是这个 pipe 返回的 Observable.

subscribe 内部,this 就是 pipe 返回的新 Observable,operator 指向 filterOperator,source 指向 fromEvent 返回的原始 Observable:

首先利用 TypeScript 对象结构语法,object destructing,将 this.operator 字段赋给变量 Operator,然后以原始 Observable 作为上下文,调用 filter Operator.
这样,pipe 返回的 Observable 上进行订阅,会传递到原始 Observable 的 subscribe 操作:
当我们在键盘上随便敲击一个字符后,触发 MouseEvent 对应的 handler,在 handler 里调用 Observer 的 next 操作。

next 操作最后会触发 filtersubscriber predicate 属性即应用开发人员传入 filter Operator 的匿名函数:

filter 输入参数也是一个函数,该函数的输入即 MouseEvent:
fromEvent 新建的 Observable,其实现逻辑内部,同样调用了 subscriber 的 next 方法来发射值。同时 fromEvent 返回的 Observable 同其他创建操作符比如 of 的特色之处,就在于其能够响应各种事件,比如 document 的 keyup 事件。

这种事件注册机制,是在上图 setupSubscription 函数里实现的。
注册的具体实现,采取了浏览器原生提供的 addEventListener,调用者为 document 全局对象,传入的 eventName 为 keyup,handler 即 fromEvent 内部实现,即上图绿色高亮区域内的代码。
export declare function filter<T>(predicate: (value: T, index: number) => boolean, thisArg?: any): MonoTypeOperatorFunction<T>;

filter Operator 接受一个 predicate 作为输入参数,返回一个类型为 MonoTypeOperatorFunction 的函数。
这里的 T 为类型参数。MonoType 对应 T,意思是单参数。
MonoTypeOperatorFunction 是一种特殊的 OperatorFunction,当后者的输入和返回参数都相同时,即特殊化为单类型 OperatorFunction:
OperatorFunction 又是一种特殊的 UnaryFunction(一元函数),当一元函数的输入和输出类型都是一个 Observable 时,即特殊化成了 OperatorFunction.

边栏推荐
- When the R language output rmarkdown is in other formats (such as PDF), an error is reported, latex failed to compile stocks Tex. solution
- [Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter V exercises]
- Kotlin - improved decorator mode
- 道路建设问题
- sitesCMS v3.0.2发布,升级JFinal等依赖
- Tencent cloud tdsql database delivery and operation and maintenance Junior Engineer - some questions of Tencent cloud cloudlite certification (TCA) examination
- The foreground uses RSA asymmetric security to encrypt user information
- Deeply understand the mvcc mechanism of MySQL
- regular expression
- Cache penetration and bloom filter
猜你喜欢

双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
![[data mining review questions]](/img/96/00f866135e06c4cc0d765c6e499b29.png)
[data mining review questions]

剑指 Offer 12. 矩阵中的路径
![[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]](/img/47/78d9dd098dcb894ba1f459873d5f52.png)
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]

今日睡眠质量记录77分

对业务的一些思考

Flink SQL knows why (7): haven't you even seen the ETL and group AGG scenarios that are most suitable for Flink SQL?

人身变声器的原理

Idea full text search shortcut ctr+shift+f failure problem

(first) the most complete way to become God of Flink SQL in history (full text 180000 words, 138 cases, 42 pictures)
随机推荐
【数据库原理及应用教程(第4版|微课版)陈志泊】【SQLServer2012综合练习】
2022-01-27 redis cluster cluster proxy predixy analysis
[combinatorics] permutation and combination (multiple set permutation | multiple set full permutation | multiple set incomplete permutation all elements have a repetition greater than the permutation
已解决TypeError: Argument ‘parser‘ has incorrect type (expected lxml.etree._BaseParser, got type)
SQL learning notes (I)
Sword finger offer 15 Number of 1 in binary
Four problems and isolation level of MySQL concurrency
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]
高效能人士的七个习惯
Fabric.js 更换图片的3种方法(包括更换分组内的图片,以及存在缓存的情况)
February 14, 2022, incluxdb survey - mind map
关于CPU缓冲行的理解
Will Huawei be the next one to fall
[Exercice 5] [principe de la base de données]
A large select drop-down box, village in Chaoyang District
[network counting] Chapter 3 data link layer (2) flow control and reliable transmission, stop waiting protocol, backward n frame protocol (GBN), selective retransmission protocol (SR)
18W word Flink SQL God Road manual, born in the sky
Flink SQL knows why (12): is it difficult to join streams? (top)
剑指 Offer 17. 打印从1到最大的n位数
【数据库原理及应用教程(第4版|微课版)陈志泊】【第四章习题】