rxjs - RxJs动态throttleTime持续时间又名获取滚动开始事件流
问题描述
你好,
首先,感谢您阅读本文。
我想处理滚动事件流,我想对滚动开始做出反应并忽略滚动事件的爆发,直到流被认为是不活动的(时间限制)。所以延迟后我想重复同样的事情。
到目前为止,这是我的解决方案:
import { fromEvent } from 'rxjs';
import { throttle, debounceTime } from 'rxjs/operators';
const stream = fromEvent(window, 'scroll');
const controllerStream = stream.pipe(debounceTime(500));
this.sub = stream
.pipe(
throttle(() => controllerStream, {
leading: true,
trailing: false,
})
)
.subscribe(() => {
// react on scroll-start events
});
有没有更好的办法?我正在考虑像throttleTime,debounce,debounceTime这样的运营商......但我找不到符合我需要的配置
谢谢
解决方案
我制作了第三个版本,将我的解决方案封装到基于@backtick 答案的自定义运算符中。这个解决方案有问题吗?内存泄漏什么的?我不确定内部 controllerStream 是否会正确销毁或完全销毁。
const firstAfterInactiveFor = (ms) => (source) => {
const controllerStream = source.pipe(debounceTime(ms));
return source
.pipe(
throttle(() => controllerStream, {
leading: true,
trailing: false
})
)
};
// This achieves the desired behavior.
stream
.pipe(
firstAfterInactiveFor(500)
)
.subscribe(() => {
console.log("scroll-start");
});
这是与所有三个比较的codepen: https ://codepen.io/luckylooke/pen/zYvEoyd
编辑:带有日志和取消订阅按钮的更好示例 https://codepen.io/luckylooke/pen/XWmqQBg
推荐阅读
- php - 如何将数据从一台服务器传输到另一台服务器
- java - 截断表表最优解
- reactjs - 在嵌套的放置目标中放置一个组件会给出错误
- python - 使用 lambda 计算 pandas 数据框中的值
- raspberry-pi - 无法找到包 ros-kinetic-depthimage-to-laserscan(在 Raspberry Pi 上)
- css - 带列的水平布局:如何在列大小固定且列数未知的情况下自动调整容器大小
- google-app-engine - 从 Golang AppEngine 快速轻松地发布到 Slack Webhook
- google-sheets - 将一个单元格链接到多个单元格排除 Google 表格中的中间范围
- php - 无法获取 coingecko API 的信息
- admob - 如何通过代码从 aerserv 关闭全屏横幅广告?