简体   繁体   English

如何在零时间内获得RxJS Observable事件?

[英]How to get RxJS Observable events in zero time?

I'm collecting all the events of an Observable to a data array: 我正在将一个Observable的所有事件收集到data数组中:

 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> 

Is it possible to "foresee the future" and get the same data array without waiting 2 seconds ? 是否有可能“预见未来”并获得相同的data阵列而无需等待2秒钟

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. 为了澄清,我试图找到一种方法以某种方式用自定义计时器/调度程序包装一个给定的Observable(在上面的例子中为obs$ ),这样我就可以立即获得事件。

You can create an instance of the VirtualTimeScheduler and can specify it in the call to interval . 您可以创建VirtualTimeScheduler的实例,并可以在interval调用中指定它。

If you then call flush on the scheduler after subscribing, the events will be emitted immediately: 如果您在订阅后在调度程序上调用flush ,则会立即发出事件:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM