• rxjs Observable of 操作符的单步调试分析


    看这段最简单的代码:

    import { Observable, of } from 'rxjs';
    
    const observable = of(1, 2, 3);
    
    observable.subscribe((message) => {
      console.log(message);
    }); 
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    输出:

    输入的 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');
      }
    );
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    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);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    输出:

    该 Observable 在输出 4 个整数后停止发射值。

  • 相关阅读:
    Java IO流(详解)
    Spring Boot常用的参数验证技巧和使用方法
    PostgreSQL常用指令
    XTU-OJ 1178-Rectangle
    Redis高可用、持久化及性能管理
    经典卷积和深度卷积的神经网络
    企业级监控方案——zabbix!(下)
    204.计数质数 | 372.超级次方
    线下商家卖货难、拓客难、引流难,不如学习一下怎么结合O2O电商
    SaaSBase:K2是什么?
  • 原文地址:https://blog.csdn.net/i042416/article/details/124925548