Observable.of turn async

风格不统一 提交于 2020-01-02 05:40:09

问题


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>

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.

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


回答1:


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');

This will log out:

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

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




回答2:


This is because observable.of has by default a null Scheduler. Check the official docs:

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.

So just import an async Scheduler

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

and send it as the second parameter

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



回答3:


The recent rxJS framework seems to favor asyncScheduler (import from rxjs) instead of async (import from "rxjs/internal/scheduler/async"). Example:

import { of asyncScheduler } from "rxjs";

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

More information about rxJS schedulers can be found here.



来源:https://stackoverflow.com/questions/40529599/observable-of-turn-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!