首页 > 解决方案 > 带去抖动的 BehaviorSubject 订阅

问题描述

我有 BehaviorSubject 属性

public results$ = new BehaviorSubject(null);

假设我订阅了这个

this.results$.subscribe(() => this.find());

每次我在输入元素内按键盘上的任何键时都会调用订阅。因此,为了防止对服务器的许多请求,我添加了 debounceTime()

this.results$
   .pipe(debounceTime(500))
   .subscribe(() => this.find());

但是我需要立即调用第一个this.find()而没有任何反跳。

我怎样才能做到这一点?

标签: angularrxjsbehaviorsubject

解决方案


我建议您使用throttleTime而不是 debounceTime。它传播第一个值,然后等待指定的时间量。

还将 更改BehaviorSubjectSubject

公开结果$ = new Subject();

this.results$
   .pipe(
         filter(value => !!value && value.length >= 3),
         throttleTime(500))
   .subscribe(() => this.find());

请在此处阅读有关 throttleTime、auditTime 和 debounceTime 的信息 - https://rxjs-dev.firebaseapp.com/guide/operators


推荐阅读