RxJS中的Scheduler


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/11/25/RxJS%E4%B8%AD%E7%9A%84Scheduler/

摘要

本文主要讲述了:

  1. 什么是 Scheduler
  2. Scheduler 分类

正文

什么是 Scheduler

Scheduler,意为调度程序。

Scheduler 用于控制如何推送通知。

示例:使用asyncScheduler

使用前:同步推送

输入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="https://unpkg.com/core-js-bundle/index.js"></script>
<script src="https://unpkg.com/regenerator-runtime/runtime.js"></script>
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script src="https://unpkg.com/@reactivex/rxjs@6/dist/global/rxjs.umd.js"></script>
<script type="text/babel">
const observable = new rxjs.Observable(function (subscriber) {
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
});

console.log('begin');
observable.subscribe({
next(x) {
console.log(x);
},
});
console.log('end');
</script>
</head>
<body></body>
</html>

输出:

1
2
3
4
5
begin
1
2
3
end

使用后:异步推送

输入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="https://unpkg.com/core-js-bundle/index.js"></script>
<script src="https://unpkg.com/regenerator-runtime/runtime.js"></script>
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script src="https://unpkg.com/@reactivex/rxjs@6/dist/global/rxjs.umd.js"></script>
<script type="text/babel">
const observable = new rxjs.Observable(function (subscriber) {
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
}).pipe(rxjs.operators.observeOn(rxjs.asyncScheduler));

console.log('begin');
observable.subscribe({
next(x) {
console.log(x);
},
});
console.log('end');
</script>
</head>
<body></body>
</html>

输出:

1
2
3
4
5
begin
end
1
2
3

Scheduler 分类

null

未传递任何 Scheduler。此时通知将以同步的形式推送。

asyncScheduler

此时通知将以异步的形式推送。

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/11/25/RxJS%E4%B8%AD%E7%9A%84Scheduler/


本文对你有帮助?请支持我


支付宝
微信