简体   繁体   English

带去抖动的 BehaviorSubject 订阅

[英]BehaviorSubject subscription with debounce

I have BehaviorSubject property我有 BehaviorSubject 属性

public results$ = new BehaviorSubject(null);

Lets'say I have a subscription to this假设我订阅了这个

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

Subscription in being invoked each time when I press any key on keyboards inside input element.每次我在输入元素内按键盘上的任何键时都会调用订阅。 So, to prevent many requests to the server, I added debounceTime()因此,为了防止对服务器的许多请求,我添加了 debounceTime()

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

But I need to invoke the first this.find() without any debounce, just immediately.但是我需要立即调用第一个this.find()而没有任何反跳。

How can I do that?我怎样才能做到这一点?

I would suggest you to use throttleTime instead of debounceTime.我建议你使用throttleTime而不是 debounceTime。 It propagates the first value and then wait for the specified amount of time.它传播第一个值,然后等待指定的时间量。

Also change the BehaviorSubject to Subject .还将BehaviorSubject更改为Subject

public results$ = new Subject();公开结果$ = new Subject();

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM