RxJS 系列 – Custom Operator
前言
虽然 RxJS 提供了非常多的 Operators. 但依然会有不够用的时候. 这时就可以自定义 Operator 了.
Operator Is Just a Function Observable => Observable
Operator 只是一个函数.
timer(1000).pipe(obs => obs).subscribe();
它接收一个 Observable 返回一个 Observable.
Operator 都是放在管道 (pipe) 内的, 所以从源头 Observable 一直传递下去.
每一个 Operator 接收 upstream(上游) 的 Observable 并且返回一个 Observable (通常是新的一个) 给 downstream(下游).
每一个 Operator 就是对发布值的加工处理.
Standard Operator
source 源头
首先我们有个源头
const source = timer(1000);
每一秒发布一次
Upstream / Downstream Observable
接着搞一个 pipe 和 operator.
const source = timer(1000);
source
.pipe(upstreamObs => {
console.log(upstreamObs === source); // true const downstreamObs = new Observable();
return downstreamObs;
})
.subscribe(v => console.log(v));
可以看到 operator 函数接收的就是 upstream 的 Observable, 然后返回一个新的 Observable 到 downstream.
Connect Upstream and Downstream
downstream to upstream
当 downstream 被 subscribe, 我们 subscribe upstream
当 downstream 被 unsubscribe, 我们 unsubscribe upstream
const source = timer(1000);
source
.pipe(upstreamObs => {
const downstreamObs = new Observable(subscriber => { // 当 downstream Observable 被订阅以后, 我们才订阅 upstream Observable
const upstreamSub = upstreamObs.subscribe(); return () => {
// 当 downstream 被退订以后, 我们也要退订 upstream Observable
upstreamSub.unsubscribe();
}; }); return downstreamObs;
})
.subscribe(v => console.log(v));
upstream to downstream
当接收到 upstream 发布时, 我们也发布到 downstream
const downstreamObs = new Observable(subscriber => {
const upstreamSub = upstreamObs.subscribe({
next: upstreamValue => {
const downStreamValue = upstreamValue + 'downstream value'; // decorate value for downstream
subscriber.next(downStreamValue); // 发布到 downstream
},
error: error => subscriber.error(error), // 转发去 downstream
complete: () => subscriber.complete(), // 转发去 downstream
});
return () => {
upstreamSub.unsubscribe();
};
});
小结
从上面几招可以看出来, 主要就是 upstream 和 downstream 中间的关系.
如何订阅, 退订, 发布 value 等等. 上面只是给一个简单直观的例子. 真实场景中, upstream 和 downstream 发布时机, 往往是不一致的 (比如 upstream 发布 1 次后, downstream 可能发布多次)
Operator with Config
只要把 Operator 包装成工厂函数就可以支持 Config 了
function myOperator(config: { dependObs: Observable<unknown> }): OperatorFunction<number, string> {
const { dependObs }= config;
return upstreamObs => {
const downstreamObs = new Observable<string>(subscriber => {
// 订阅 depend
const dependObsSub = dependObs.subscribe(() => console.log('do something'));
const upstreamSub = upstreamObs.subscribe({
next: upstreamValue => {
const downStreamValue = upstreamValue + 'downstream value'; // decorate value for downstream
subscriber.next(downStreamValue); // 发布到 downstream
},
error: error => subscriber.error(error), // 转发去 downstream
complete: () => {
// 释放 depend
dependObsSub.unsubscribe();
subscriber.complete();
},
});
return () => {
upstreamSub.unsubscribe();
// 释放 depend
dependObsSub.unsubscribe();
};
});
return downstreamObs;
};
}
const source = timer(1000);
const dependObs = new Subject();
source.pipe(myOperator({ dependObs })).subscribe(v => console.log(v));
一个 Factory 函数, 通过配置生产 Operator。
OperatorFunction 定义了 Operator 接口, 它是加入了泛型的 Observable => Observable.
如果 upstream 和 downstream 的类型是一样的话可以用它的简化版本 MonoTypeOperatorFunction<T>

Unsubscribe dependency stream
比如说像 takeUntil operator
const obs = timer(0, 1000); // 0..1..2..3..4..5
obs.pipe(takeUntil(timer(3000))).subscribe(v => console.log(v)); // 0..1..2
它内部会 subscribe timer$,timer$ 就是它的 dependency observable。
如果在还没有到 3 秒的时候,这个 observable 就被 unsubscribe 了,那 takeUntil operator 内部就要提前去 unsubscribe timer$。
同理,如果这个 observable 在还没有到 3 秒的时候,就被 error 或 complete 了,那 takeUntil operator 内部也需要提前去 unsubscribe timer$。
总之,我们在设计 operator 时,一定要顾虑到 upstream 的 error / complete 和 downstream 的 unsubscribe 对 dependency observable 的影响。
RxJS 系列 – Custom Operator的更多相关文章
- [RxJS] Error handling operator: catch
Most of the common RxJS operators are about transformation, combination or filtering, but this lesso ...
- [转]VS Code 扩展 Angular 6 Snippets - TypeScript, Html, Angular Material, ngRx, RxJS & Flex Layout
本文转自:https://marketplace.visualstudio.com/items?itemName=Mikael.Angular-BeastCode VSCode Angular Typ ...
- [RxJS] Learn How To Use RxJS 5.5 Beta 2
The main changes is about how you import rxjs opreators from now on. And introduce lettable opreator ...
- RxJS——调度器(Scheduler)
调度器 什么是调度器?调度器是当开始订阅时,控制通知推送的.它由三个部分组成. 调度是数据结构.它知道怎样在优先级或其他标准去存储和排队运行的任务 调度器是一个执行上下文.它表示任务在何时何地执行(例 ...
- C++复制对象时勿忘每一部分
现看这样一个程序: void logCall(const string& funcname) //标记记录 { cout <<funcname <<endl; } cl ...
- Flink - DataStream
先看例子, final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); D ...
- 重载new delete操作符是怎么调用的
自定义的new操作符是怎么对英语new 一个对象的?自定义的delete操作符什么情况下得到调用?new一个对象时出现异常需要我操心内存泄露吗?下面的一个例子帮我们解开所有的疑惑. 1. 调用规则 ...
- 算法竞赛向 C++ Standard Library 使用速查
因网络上 STL 教程大多零散且缺乏严谨性,本文对算法竞赛所需 C++ Standard Library 做了一个较为全面的总结. 全文主要参考以下文档: Containers library - c ...
- [RxJS] Create a Reusable Operator from Scratch in RxJS
With knowledge of extending Subscriber and using source.lift to connect a source to a subscriber, yo ...
- [RxJS] Creation operator: of()
RxJS is a lot about the so-called "operators". We will learn most of the important operato ...
随机推荐
- 开源免费的专注于建立大型个人知识库推荐-Trilium Notes
Trilium Notes是一个分层的笔记应用程序,专注于建立大型个人知识库. 支持相当丰富的 markdown,包括 mermaid 和 latex,而且即时渲染,和 typora 一样.支持代码类 ...
- K8S 中的 CRI、OCI、CRI shim、containerd
哈喽大家好,我是咸鱼. 好久没发文了,最近这段时间都在学 K8S.不知道大家是不是和咸鱼一样,刚开始学 K8S.Docker 的时候,往往被 CRI.OCI.CRI shim.containerd 这 ...
- [oeasy]python0129_unicode_中文字符序号_十三道大辙_字符编码解码_eval_火星文
unicode 中文字符分类 回忆上次内容 字符集 从博多码 到 ascii 再到 iso-8859 系列 各自割据 如何把世界上各种字符统进行编码 unicode顺势而生不断进化 不过字符总量超 ...
- [oeasy]python0010 - python虚拟机解释执行py文件的原理
解释运行程序 回忆上次内容 我们这次设置了断点 设置断点的目的是更快地调试 调试的目的是去除bug 别害怕bug 一步步地总能找到bug 这就是程序员基本功 调试deb ...
- 2023 CSP 游记
目录 \(\text{CSP-J}\) 游记 \(\text{CSP-S}\) 游记 \(\text{CSP-J}\) 游记 省流:\(\text{B}\) 题挂了 \(100\text{ pts}\ ...
- 使用uWSGI+nginx部署Django项目(Ubuntu)
对于uwsgi+nginx的部署方式,它的访问关系大概是: 1 the web client <-> the web server <-> the socket <-&g ...
- CF1956B Nene and the Card Game 题解
Nene and the Card Game 题意 有 \(2n\) 张牌,\(1,2,3,\dots,n\) 皆有两张. 有两个人在玩游戏,每个人有 \(n\) 张卡片,当一人出了一张编号为 \(k ...
- 记一次在openEuler系统下离线编译升级到openssh9.8p1
缘起 由于某个项目上甲方对服务器进行漏洞扫描,系统为:openEuler 22.03 (LTS-SP4).提示现有OpenSSH版本存在漏洞,需要升级到openssh-9.8p1的版本(目前最新),遂 ...
- DSCL:已开源,北京大学提出解耦对比损失 | AAAI 2024
监督对比损失(SCL)在视觉表征学习中很流行.但在长尾识别场景中,由于每类样本数量不平衡,对两类正样本进行同等对待会导致类内距离的优化出现偏差.此外,SCL忽略了负样本之间的相似关系的语义线索.为了提 ...
- OpenAI深夜丢炸弹硬杠谷歌搜索
这几年科技变革太快,AI更是飞速发展,作为一名IT老兵,使用过的搜索引擎也是一换再换.这不,刚消停了一段时间的OpenAI又丢出一个炸弹SearchGPT,直接跟谷歌掀桌子了. 1.谷歌搜索的无奈 早 ...