RxJS - 使用订阅

当创建可观察对象时,要执行可观察对象,我们需要订阅它。

count() 运算符

下面是如何订阅可观察对象的简单示例。

示例 1

import { of } from 'rxjs';
import { count } from 'rxjs/operators';

let all_nums = of(1, 7, 5, 10, 10, 20);
let final_val = all_nums.pipe(count());
final_val.subscribe(x => console.log("计数为 "+x));

输出

计数为 6

订阅有一个名为 unsubscribe() 的方法。调用 unsubscribe() 方法将删除用于该可观察对象的所有资源,即可观察对象将被取消。以下是使用 unsubscribe() 方法的一个实际示例。

示例 2

import { of } from 'rxjs';
import { count } from 'rxjs/operators';

let all_nums = of(1, 7, 5, 10, 10, 20);
let final_val = all_nums.pipe(count());
let test = final_val.subscribe(x => console.log("计数为 "+x));
test.unsubscribe();

订阅存储在变量 test 中。我们已使用 test.unsubscribe() 可观察对象。

输出

计数为 6