首页 > 解决方案 > 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这样的运营商......但我找不到符合我需要的配置

谢谢

标签: rxjs

解决方案


我制作了第三个版本,将我的解决方案封装到基于@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


推荐阅读