可观察到的异步 [英] Observable.of turn async

查看:72
本文介绍了可观察到的异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要模拟包装成可观察状态的http调用.我最初的想法是简单地使用类似于Promise.resolveObservable.of,但是它似乎并没有达到我的预期:

I'm about to mock a http call wrapped into observable. My initial idea was to simply use Observable.of similar to Promise.resolve, but it does not seem to work as I expected:

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'))异步运行(这就是我想要的).只要我要测试微调框,就不会显示同步调用.

It seems that Observable.of runs synchronously while Rx.Observable.from(Promise.resolve('from1')) runs asynchronously (that is what I want). As long as I want to test the spinner is displayed, the synchronous call is not an option for me.

例如,当我有某种解决方案时延迟它或设置一个计时器:

There is some kind of solution when I e.g. delay it or set a timer:

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

但这对我来说也不是很好.

but this also does not look good to me.

如何将Observable.of设置为异步运行?从Promise转换它似乎是一个过大的杀伤力.

How can I turn Observable.of to run asynchronously? Converting it from Promise seems like an overkill.

推荐答案

如果您希望可观察对象的行为不同,则可以将其传递给调度程序.您可以使用异步调度程序,使调用堆栈一经清除就使可观察到的发射值. 明智的代码如下所示:

If you want an observable of to behave differently you can pass it a scheduler. You could use the async scheduler to make the observable emit values as soon as the call stack is clear. Code wise this would look like this:

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,控制台

Working jsbin example here: http://jsbin.com/cunatiweqe/6/edit?js,console

这篇关于可观察到的异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆