【问题标题】:RxJS custom scheduler for requestAnimationFrame用于 requestAnimationFrame 的 RxJS 自定义调度程序
【发布时间】:2019-11-19 21:36:38
【问题描述】:

我知道 rxjs 有一个内置的animationFrameScheduler,但我很确定我不能用它来完成我想要的。

基本上我想通过requestAnimationFrame 限制一些事件。我将如何在订阅中做到这一点是:

let taskId;

fromEvent(...)
.subscribe(args => {

  if (taskId) {
    cancelAnimationFrame(taskId);
  }

  taskId = requestAnimationFrame(() => {
    performMyAction(args);
    taskId = null;
  });
});

发生的事情是我想限制事件并且只执行每个动画帧的最后一个事件。

我尝试过throttleTime(0, animationFrameScheduler)observeOn(animationFrameScheduler),但似乎都没有按照我的意愿行事。

我的下一个想法是创建一个可以执行此操作的自定义调度程序。我知道我应该创建一个实现ScheduleLike 的类,但在那之后似乎没有关于该类的不同方法应该做什么以及参数的含义的文档。

此外,尝试阅读现有调度程序的源代码是一种不透明的继承混乱,对我自己的实现没有用。

所以我的问题是;我如何使用animationFrameScheduler 以这种方式实际限制我的事件,或者我如何学习如何构建自己的调度程序?

【问题讨论】:

  • 听起来很适合堆叠闪电战
  • “只执行每个动画帧的最后一个事件”是什么意思?

标签: rxjs


【解决方案1】:

内置animationFrame scheduleraudit operator 相结合,从静音时间窗口获取最后一个值应该可以完成这项工作。

见代码示例:

const { of, from, animationFrameScheduler, asyncScheduler, interval } = rxjs;
const { audit, toArray } = rxjs.operators;
 
 const numbers = Array.from({ length: 100 }).map((_, i) => i);

from(numbers, asyncScheduler).pipe(
  audit(e => of(null, animationFrameScheduler))
).subscribe(e => console.log(e));
<script src="https://unpkg.com/rxjs@6.5.3/bundles/rxjs.umd.min.js"></script>

【讨论】:

  • 是的!这行得通,谢谢。不知道为什么我没有想到。我最终使用了auditTime(0, animationFrameScheduler),它的行为完全符合我的预期。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多