如何在零时间内获得RxJS Observable事件? [英] How to get RxJS Observable events in zero time?

查看:60
本文介绍了如何在零时间内获得RxJS Observable事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个Observable的所有事件收集到数据数组:

I'm collecting all the events of an Observable to a data array:

const obs$ = Rx.Observable
  .interval(500)
  .take(4);

let data = [];
const start = performance.now();

obs$.subscribe(
  value => {
    data.push({
      time: performance.now() - start,
      data: value
    });
  },
  () => {},
  () => {
    console.log(JSON.stringify(data, null, 2));
  }
);

<script src="https://unpkg.com/rxjs@5.2.0/bundles/Rx.js"></script>

是否有可能预见未来并获得相同的数据数组没有等待2秒

Is it possible to "foresee the future" and get the same data array without waiting 2 seconds?

为了澄清,我试图找到一种方法以某种方式包装给定的Observable(Ò bs $ 在上面的示例中)带有自定义计时器/调度程序,因此我可以立即获取事件。

To clarify, I'm trying to find a way to wrap somehow a given Observable (obs$ in the example above) with a custom timer/scheduler so I could get the events immediately.

推荐答案

您可以创建 <$ c $的实例c> VirtualTimeScheduler 并且可以在 interval 的调用中指定它。

You can create an instance of the VirtualTimeScheduler and can specify it in the call to interval.

如果您在订阅后在调度程序上调用 flush ,则会立即发出事件:

If you then call flush on the scheduler after subscribing, the events will be emitted immediately:

const scheduler = new Rx.VirtualTimeScheduler();

const obs$ = Rx.Observable
  .interval(500, scheduler)
  .take(4);

let data = [];
const start = scheduler.now();

obs$.subscribe(
  value => {
    data.push({
      time: scheduler.now() - start,
      data: value
    });
  },
  () => {},
  () => {
    console.log(JSON.stringify(data, null, 2));
  }
);

scheduler.flush();

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://unpkg.com/rxjs@5.2.0/bundles/Rx.js"></script>

这篇关于如何在零时间内获得RxJS Observable事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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