代码之家  ›  专栏  ›  技术社区  ›  Ryley38

如何跳过流的第一个值,除非它是RxJS的复制粘贴?

  •  1
  • Ryley38  · 技术社区  · 11 月前

    我目前使用skip(1)来避免在键入第一个值时进行不必要的计算。然而,我发现我的用户经常使用复制粘贴来过滤数据。因此,skip(1)将跳过整个粘贴的值。

    只有当第一个键入的字符不是来自粘贴的值时,我才希望跳过它。我对复制粘贴并不感兴趣,但更感兴趣的是,第一个值可能是包含几个字符的完整过滤器。

    这是我当前的代码:

        public ngAfterViewInit(): void {
        this.quickFilterValueChange
            .pipe(
                skip(1),
                debounceTime(150),
                distinctUntilChanged(),
                tap(() => {
                    this.store.dispatch(someAction);
                }),
                takeUntilDestroyed(this.destroyRef),
            )
            .subscribe();
    }
    
    1 回复  |  直到 11 月前
        1
  •  0
  •   Naren Murali    11 月前

    你需要使用 debounceTime 并增加阈值以跳过不必要的计算,而不是 skip 其省略了初始值。

    这样做的优点是,如果字符在阈值内,则只取最后一个值,其余值将被丢弃。

    我还为添加了一个代码片段 filter 其中,我们仅在搜索字符串大于3个字符时才运行逻辑。

    public ngAfterViewInit(): void {
        this.quickFilterValueChange
            .pipe(
                // filter(() => this.searchStr.length > 3), // you can also use this to limit the initial typing of the search field.
                debounceTime(500), // <- threshold is 500ms
                distinctUntilChanged(),
                tap(() => {
                    this.store.dispatch(someAction);
                }),
                takeUntilDestroyed(this.destroyRef),
            )
            .subscribe();
    }
    
    推荐文章