当前位置:网站首页>rxjs Observable of 操作符的单步调试分析
rxjs Observable of 操作符的单步调试分析
2022-07-01 21:48:00 【汪子熙】
看这段最简单的代码:
import {
Observable, of } from 'rxjs';
const observable = of(1, 2, 3);
observable.subscribe((message) => {
console.log(message);
});
输出:
输入的 1,2,3 被当成数组处理,触发 fromArray 函数调用:
因为不存在 scheduler 调用,所以进入 subscribeToArray 分支:
subscribeToArray 的实现在一个 subscribeToArray.ts
文件里,这个文件的命名空间如下:internal/util
注意,上图第 8 行的 for 循环,显然在 of 函数调用里不会执行,而是 of 返回的 Observable 被 subscribe 时才执行。subscribeToArray 的逻辑就是,一个简单的 for 循环,循环体内依次调用 subscriber 的 next 方法,最后调用 complete 方法。
subscribeToArray 返回的函数,存储在 Observable 构造函数的 _subscribe 属性内。
然后针对这个 of 返回的 Observable 实例,调用 subscribe 方法。
of Observable 实例的 _subscribe 方法,指向的就是刚刚 subscribeToArray 返回的函数:
直到 Observable 被 subscribe,这个函数体才得以执行。在函数体的 for 循环内,逐一调用 subscriber 的 next 方法:
subscriber 并不是应用开发人员创建的,而是 rxjs 框架内部维护和使用的。subscriber 有一个属性 destination,指向 Safesubscriber,这个 safesubscriber 的 _next 属性,指向的就是应用开发人员维护的回调函数。
这段函数先后执行顺序如下图图例所示:
subscribe 除了传入一个单一的回调函数之后,还支持 error 和 complete 处理。
看下面的例子:
import {
Observable, of } from 'rxjs';
const observable = of(1, 2, 3);
observable.subscribe(
(message) => {
console.log(message);
},
() => {
},
() => {
console.log('complete');
}
);
complete 方法和 next 方法的执行逻辑类似,唯一区别是在 for 循环体执行完毕之后触发:
由此可见,of 创建的 Observable 是 cold Observable.
如果是一个周期性发射数据的 Observable,我们还可以使用 unsubscribe 对其取消订阅。看下面的代码:
import {
interval } from 'rxjs';
const observable = interval(1000);
const subscription = observable.subscribe((x) => console.log(x));
setTimeout(() => {
subscription.unsubscribe();
}, 4500);
输出:
该 Observable 在输出 4 个整数后停止发射值。
边栏推荐
猜你喜欢
Ida dynamic debugging apk
分享一个一年经历两次裁员的程序员的一些感触
Mysql——》索引存储模型推演
园区全光技术选型-中篇
【MySQL】索引的分类
Dark horse programmer - software testing - stage 06 2-linux and database-01-08 Chapter 1 - description of the content of the Linux operating system stage, description of the basic format and common fo
完全注解的ssm框架搭建
PyTorch磨刀篇|argmax和argmin函数
What is the difference between PMP and NPDP?
3DE 资源没东西或不对
随机推荐
性能测试计划怎么编写
Mysql——》索引存储模型推演
SAP UI5 应用开发教程之一百零四 - SAP UI5 表格控件的支持复选(Multi-Select)以及如何用代码一次选中多个表格行项目
Gaussdb (DWS) active prevention and troubleshooting
#yyds干货盘点# 解决名企真题:扭蛋机
[jetcache] how to use jetcache
Ida dynamic debugging apk
There is no signal in HDMI in computer games caused by memory, so it crashes
Slope compensation
友善串口助手使用教程_友善串口调试助手怎么进行配置-友善串口调试助手使用教程…
MySQL中对于索引的理解
Learn MySQL from scratch - database and data table operations
Chapter 9 Yunji datacanvas company has been ranked top 3 in China's machine learning platform market
Mask wearing detection method based on yolov5
Is PMP certificate really useful?
Clean up system cache and free memory under Linux
LC501. 二叉搜索树中的众数
Configure filter
Redis configuration and optimization
keras训练的H5模型转tflite