Observable.of turn async

試著忘記壹切 提交于 2019-12-05 18:18:39

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

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

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.

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