gpt4 book ai didi

用于 requestAnimationFrame 的 RxJS 自定义调度程序

转载 作者:行者123 更新时间:2023-12-04 10:59:14 33 4
gpt4 key购买 nike

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

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

let taskId;

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

if (taskId) {
cancelAnimationFrame(taskId);
}

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

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

我已经尝试了 throttleTime(0, animationFrameScheduler)observeOn(animationFrameScheduler) 似乎都没有达到我想要的效果。

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

此外,尝试阅读现有调度器的源代码是一种不透明的继承困惑,并且在实现我自己的调度器时没有用。

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

最佳答案

内置 animationFrame scheduler结合 audit 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>

关于用于 requestAnimationFrame 的 RxJS 自定义调度程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58943170/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com