首页 > 解决方案 > 在特定条件下跳过/忽略来自事件订阅的 Observable

问题描述

当条件为真时,我想跳过/忽略fromEvent() observable的订阅:当我不想订阅 observable 因为它直接滚动到下一个项目并且我的目标是等待用户交互滚动到下一个我的界面上的项目..this.currentPosition === this.vc.getScrollPosition()[1]

fromEvent(window, 'scroll').pipe(
    distinctUntilChanged(),
    debounceTime(1000)
)
    .subscribe(
        (event) => {

            const current = this.positions.find(e => e.name === this.currentSectionName);
            const indexOfCurrent = this.positions.indexOf(current);

            if (indexOfCurrent + 1 === this.positions.length) {
                // stay in the same position if it's the last item
                this.vc.scrollToPosition([0, current.position]);
                this.currentPosition = current.position;

            } else {
                // move to next position if it's not the last item
                const next = this.positions[indexOfCurrent + 1];
                this.vc.scrollToPosition([0, next.position]);
                this.currentPosition = next.position;
            }
        }

    );

标签: javascriptangulartypescriptrxjs

解决方案


您可以在管道中过滤它。

fromEvent(window, 'scroll').pipe(
    filter( () => this.currentPosition !== this.vc.getScrollPosition()[1] ),
    distinctUntilChanged(),
    debounceTime(1000)
)

推荐阅读