RxJS -- Subscription
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的更多相关文章
- RxJS之Subject主题 ( Angular环境 )
一 Subject主题 Subject是Observable的子类.- Subject是多播的,允许将值多播给多个观察者.普通的 Observable 是单播的. 在 Subject 的内部,subs ...
- RxJS - Subject(转)
Observer Pattern 观察者模式定义 观察者模式又叫发布订阅模式(Publish/Subscribe),它定义了一种一对多的关系,让多个观察者对象同时监听某一个主题对象,这个主题对象的状态 ...
- 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 (四)第五节: ...
- 如何在AngularX 中 使用ngrx
ngrx 是 Angular框架的状态容器,提供可预测化的状态管理. 1.首先创建一个可路由访问的模块 这里命名为:DemopetModule. 包括文件:demopet.html.demopet.s ...
- Angular4 组件通讯方法大全
组件通讯,意在不同的指令和组件之间共享信息.如何在两个多个组件之间共享信息呢. 最近在项目上,组件跟组件之间可能是父子关系,兄弟关系,爷孙关系都有.....我也找找了很多关于组件之间通讯的方法,不同的 ...
- ngRx 官方示例分析 - 4.pages
Page 中通过构造函数注入 Store,基于 Store 进行数据操作. 注意 Component 使用了 changeDetection: ChangeDetectionStrategy.OnPu ...
- 用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 第三 ...
- Angular4学习笔记(十)- 组件间通信
分类 父子组件通信 非父子组件通信 实现 父子 父子组件通信一般使用@Input和@Output即可实现,参考Angular4学习笔记(六)- Input和Output 通过Subject 代码如下: ...
- angular组件之间的通讯
组件通讯,意在不同的指令和组件之间共享信息.如何在两个多个组件之间共享信息呢. 最近在项目上,组件跟组件之间可能是父子关系,兄弟关系,爷孙关系都有.....我也找找了很多关于组件之间通讯的方法,不同的 ...
随机推荐
- Android开发中用到的第三方框架汇总
最近上网搜索了一些框架资料,整理了以下常用框架,希望在项目中有所帮助. 1.网络请求框架 android-async-http 该网络框架的介绍文章地址:http://www.cnblogs.com/ ...
- List转换成JSON对象报错(四)
List转换成JSON对象 1.具体错误如下 Exception in thread "main" java.lang.NoClassDefFoundError: org/apac ...
- 错误代码: 1111 Invalid use of group function
1.错误描述 1 queries executed, 0 success, 1 errors, 0 warnings 查询:update t_user_info t inner join t_pro_ ...
- C#中各种计时器 Stopwatch、TimeSpan
1.使用 Stopwatch 类 (System.Diagnostics.Stopwatch)Stopwatch 实例可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间.在典型的 St ...
- Java中的throw和throws的区别
Java中的throw和throws的区别 1.throw关键字用于方法体内部,而throws关键字用于方法体部的方法声明部分: 2.throw用来抛出一个Throwable类型的异常,而throws ...
- js 函数中的 return+匿名函数
今天一个刚学js的朋友给了我一段代码问为什么方法不执行,代码如下: 代码如下: function makefunc(x) { return function (){ return x; } } ...
- freemarker中的left_pad和right_pad(十五)
freemarker中的left_pad和right_pad 1.简易说明 (1)left_pad 距左边 (2)right_pad 距右边 (3)当仅仅只有一个参数时,插入的是空白:当有两个参数时, ...
- 手机端仿ios的省市县3级联动脚本一
一,图片实例 二,代码 2.1,代码 $('#provinceCity_fu').click(function(){ var $this = $(this); new Picker({ "t ...
- 20165304《JAVA程序设计》第二周学习总结
课本内容总结 第一章 1.标识符与关键字 (1) 标识符由字母.数字.下划线"_".美元符号"$"组成,第一个字符不能是数字. 不能把java关键字和保留字作为 ...
- Autofac高级用法之动态代理
前言 Autofac的DynamicProxy来自老牌的Castle项目.DynamicProxy(以下称为动态代理)起作用主要是为我们的类生成一个代理类,这个代理类可以在我们调用原本类的方法之前,调 ...