我将模拟包装成可观察的http调用。我最初的想法是简单地使用Observable.of
类似Promise.resolve
,但它似乎没有工作,如我所料:
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/[email protected]/dist/global/Rx.umd.js"></script>
似乎Observable.of
同步运行而Rx.Observable.from(Promise.resolve('from1'))
异步运行(这就是我想要的)。只要显示我想测试的微调器,同步调用就不是我的选择。
有某种形式的解决方案时,我如延迟,或设置一个计时器:
Rx.Observable.of('of1').delay(0).subscribe...
但这也并不好看我。
我怎么能拒绝Observable.of
异步运行?从Promise转换它似乎是一个过大的杀伤力。
如果您希望可观察对象的行为不同,可以将其传递给调度程序。您可以使用异步调度程序,以确保在调用堆栈清除后就可以观察到发射值。明智的代码如下所示:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句