本文介绍了如何在零时间内获得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.

推荐答案

您可以创建并且可以在 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事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:53
查看更多