Subscription是什么?

当subscribe一个observable的时候, 返回的就是一个subscription. 它是一个一次性对象(disposable), 它有一个非常重要的方法 ubsubscribe(), 它没有参数, 它会dispose掉subscription所持有的资源, 或者叫取消observable的执行.

第一个例子:

import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import 'rxjs/add/observable/interval'; const observable = Observable.interval(1000); const subscription = observable.subscribe(x => console.log(x)); console.log(subscription); subscription.unsubscribe(); console.log(subscription);

运行结果是这样的:

Subscriber {
closed: false,
_parent: null,
_parents: null,
_subscriptions:
[ AsyncAction {
closed: false,
_parent: [Circular],
_parents: null,
_subscriptions: null,
scheduler: [AsyncScheduler],
work: [Function],
pending: true,
state: [Object],
delay: 1000,
id: [Timeout] } ],

syncErrorValue: null,
syncErrorThrown: false,
syncErrorThrowable: false,
isStopped: false,
destination:
SafeSubscriber {
closed: false,
_parent: null,
_parents: null,
_subscriptions: null,
syncErrorValue: null,
syncErrorThrown: false,
syncErrorThrowable: false,
isStopped: false,
destination:
{ closed: true,
next: [Function: next],
error: [Function: error],
complete: [Function: complete] },
_parentSubscriber: [Circular],
_context: [Circular],
_next: [Function],
_error: undefined,
_complete: undefined } }
Subscriber {
closed: true,
_parent: null,
_parents: null,
_subscriptions: null,
syncErrorValue: null,
syncErrorThrown: false,
syncErrorThrowable: false,
isStopped: true,
destination:
SafeSubscriber {
closed: false,
_parent: null,
_parents: null,
_subscriptions: null,
syncErrorValue: null,
syncErrorThrown: false,
syncErrorThrowable: false,
isStopped: false,
destination:
{ closed: true,
next: [Function: next],
error: [Function: error],
complete: [Function: complete] },
_parentSubscriber: [Circular],
_context: [Circular],
_next: [Function],
_error: undefined,
_complete: undefined } }

注意两次控制台输出的closed属性的值是不同的, true表示已经unsubscribe()了.

在ubsubscribe之后, _subscriptions属性也变成空了, 之前它是一个数组, 说明subscription可以是多个subscriptions的组合.

毁灭函数

如果使用Observable.create方法的话, 它的参数函数可以返回一个function. 而subscription在unsubscribe这个observable的时候, 会调用这个参数函数返回的function, 看例子:

import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import 'rxjs/add/observable/interval'; const observable = Observable.create(observer => { let index = 1;
setInterval(() => {
observer.next(index++);
}, 200); return () => {
// 在这可以做清理工作
console.log('我在Observable.create返回的function里面...');
};

}); const subscription = observable.subscribe(
x => console.log(x),
err => console.error(err),
() => console.log(`complete..`)
); setTimeout(() => {
subscription.unsubscribe();
}, 1100);

运行结果:

这个例子很好的解释了我写的那一堆拗口的解释..

retry, retryWhen的原理

直接举例:

import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/retry'; const observable = Observable.create(observer => { setInterval(() => {
observer.next('doing...');
observer.error('error!!!');
}, 200); return () => {
// 在这可以做清理工作
console.log('我在Observable.create返回的function里面...');
};
}).retry(4); observable.subscribe(
x => console.log(x),
err => console.error(err),
() => console.log(`complete..`)
);

可以看到, 每次执行next之后都会有错误, 重试4次.

运行结果:

可以看到, retry/retryWhen其实的原理即是先unsubscribe然后再重新subscribe而已, 所以每次retry都会运行我所称的毁灭函数.

操作多个Subscriptions

多个subscriptions可以一起操作, 一个subscription可以同时unsubscribe多个subscriptions, 使用add方法为subscription添加另一个subscription. 对应的还有一个remove方法.

直接举官网的例子:

var observable1 = Observable.interval(400);
var observable2 = Observable.interval(300); var subscription = observable1.subscribe(x => console.log('first: ' + x));
var childSubscription = observable2.subscribe(x => console.log('second: ' + x)); subscription.add(childSubscription); setTimeout(() => {
// Unsubscribes BOTH subscription and childSubscription
subscription.unsubscribe();
}, 1000);

运行结果:

RxJS -- Subscription的更多相关文章

  1. RxJS之Subject主题 ( Angular环境 )

    一 Subject主题 Subject是Observable的子类.- Subject是多播的,允许将值多播给多个观察者.普通的 Observable 是单播的. 在 Subject 的内部,subs ...

  2. RxJS - Subject(转)

    Observer Pattern 观察者模式定义 观察者模式又叫发布订阅模式(Publish/Subscribe),它定义了一种一对多的关系,让多个观察者对象同时监听某一个主题对象,这个主题对象的状态 ...

  3. Angular 2.0 从0到1:Rx--隐藏在Angular 2.x中利剑

    第一节:Angular 2.0 从0到1 (一)第二节:Angular 2.0 从0到1 (二)第三节:Angular 2.0 从0到1 (三)第四节:Angular 2.0 从0到1 (四)第五节: ...

  4. 如何在AngularX 中 使用ngrx

    ngrx 是 Angular框架的状态容器,提供可预测化的状态管理. 1.首先创建一个可路由访问的模块 这里命名为:DemopetModule. 包括文件:demopet.html.demopet.s ...

  5. Angular4 组件通讯方法大全

    组件通讯,意在不同的指令和组件之间共享信息.如何在两个多个组件之间共享信息呢. 最近在项目上,组件跟组件之间可能是父子关系,兄弟关系,爷孙关系都有.....我也找找了很多关于组件之间通讯的方法,不同的 ...

  6. ngRx 官方示例分析 - 4.pages

    Page 中通过构造函数注入 Store,基于 Store 进行数据操作. 注意 Component 使用了 changeDetection: ChangeDetectionStrategy.OnPu ...

  7. 用VSCode开发一个asp.net core2.0+angular5项目(5): Angular5+asp.net core 2.0 web api文件上传

    第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 第二部分: http://www.cnblogs.com/cgzl/p/8481825.html 第三 ...

  8. Angular4学习笔记(十)- 组件间通信

    分类 父子组件通信 非父子组件通信 实现 父子 父子组件通信一般使用@Input和@Output即可实现,参考Angular4学习笔记(六)- Input和Output 通过Subject 代码如下: ...

  9. angular组件之间的通讯

    组件通讯,意在不同的指令和组件之间共享信息.如何在两个多个组件之间共享信息呢. 最近在项目上,组件跟组件之间可能是父子关系,兄弟关系,爷孙关系都有.....我也找找了很多关于组件之间通讯的方法,不同的 ...

随机推荐

  1. 笔记︱范数正则化L0、L1、L2-岭回归&Lasso回归(稀疏与特征工程)

    机器学习中的范数规则化之(一)L0.L1与L2范数 博客的学习笔记,对一些要点进行摘录.规则化也有其他名称,比如统计学术中比较多的叫做增加惩罚项:还有现在比较多的正则化. -------------- ...

  2. mongodb一些使用技巧或注意事项记录

    1.有的时候需要删除指定字段那一列,使用update操作.例如要删除name这一列: query  json: {"name":{$exists:true}} update jso ...

  3. 织梦dedecms列表序号从0到1开始的办法 autoindex,itemindex标签

    自增1 arclist            标签下使用 [field:global.autoindex/] 默认从1开始 channel         标签下使用 [field:global.au ...

  4. Linux显示包含全部的文件系统

    Linux显示包含全部的文件系统 youhaidong@youhaidong-ThinkPad-Edge-E545:~$ df -a 文件系统 1K-blocks 已用 可用 已用% 挂载点 /dev ...

  5. TypeError: Error #1034: 强制转换类型失败:无法将 "0.49" 转换为 mx.graphics.IFill。

    1.错误描述 TypeError: Error #1034: 强制转换类型失败:无法将 "0.49" 转换为 mx.graphics.IFill. at mx.charts.ser ...

  6. FtpHelper ftp操作类库

    FtpHelper ftp操作类库 using System; using System.Collections.Generic; using System.Linq; using System.Te ...

  7. 浏览器之window对象--javascript

    window对象代表打开的浏览器窗口,是Web浏览器所有内容的主容器.window对象是整个对象链条结构的最高层,是其他对象的父对象,在调用window对象的方法和属性时,可以省略window对象的引 ...

  8. 简述MyBatis的体系结构

    MyBatis体系结构主要由以下几个关键部分: 1.加载配置 配置有两种形式:一种是xml配置文件,另一种是java代码的注解MyBatis将SQL的配置信息加载成为一个个的MappedStateme ...

  9. 学IT应该看些书?

    第一阶段:<数据结构><数据库><算法><信息系统管理><互联网>第二阶段:<莫生气><佛经><老子>& ...

  10. javascript三角函数的使用

    其实很多编程语言里面都有数学函数,而且很多数学函数包括三角函数,只不过有些时候可能我们用的并不多,我最近在做一个h5的游戏,其中有一个需求就是射击的枪支需要更随鼠标变换位置,鼠标移动到什么地方,炮口就 ...