Observable.of 转异步

Observable.of turn async

我要模拟一个包装到 observable 中的 http 调用。我最初的想法是简单地使用类似于Promise.resolveObservable.of,但它似乎并没有像我预期的那样工作:

Rx.Observable.of('of1').subscribe(e => console.log(e));

console.log('of2');

Rx.Observable.from(Promise.resolve('from1')).subscribe(e => console.log(e));

console.log('from2');
<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.6/dist/global/Rx.umd.js"></script>

似乎 Observable.of 运行 是同步的,而 Rx.Observable.from(Promise.resolve('from1')) 运行 是异步的(这就是我想要的)。只要我想测试微调器是否显示,同步调用就不是我的选择。

当我例如延迟它或设置一个计时器:

Rx.Observable.of('of1').delay(0).subscribe...

但这对我来说也不好看。

如何将 Observable.of 异步转换为 运行?从 Promise 转换它似乎有点矫枉过正。

如果你想要一个 observable of 的行为不同,你可以给它传递一个调度程序。您可以使用异步调度程序让可观察对象在调用堆栈清除后立即发出值。 代码明智这看起来像这样:

Rx.Observable.of(1, 2, 3, Rx.Scheduler.async).subscribe(
    (val) => console.log(val)
);

console.log('first');

这将注销:

//first
//1
//2
//3

这里的工作 jsbin 示例:http://jsbin.com/cunatiweqe/6/edit?js,console

这是因为 observable.of 默认情况下有一个空调度程序。查看官方文档:

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-of

By default, it uses a null IScheduler, which means the next notifications are sent synchronously, although with a different IScheduler it is possible to determine when those notifications will be delivered.

所以只需导入一个异步调度程序

import { async } from 'rxjs/scheduler/async';

并将其作为第二个参数发送

Observable.of('of1', async).subscribe(e => console.log(e));

最近的 rxJS 框架似乎更倾向于 asyncScheduler(从 rxjs 导入)而不是 asyncimport from "rxjs/internal/scheduler/async")。示例:

import { of asyncScheduler } from "rxjs";

const ret = of(this.someVariable, asyncScheduler);

可以找到有关 rxJS 调度器的更多信息 here