如何使可观察到的反跳时间成为条件 [英] How to make observable debounceTime conditional

查看:89
本文介绍了如何使可观察到的反跳时间成为条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对元素输入事件进行了简单的反跳,如下所示:

I have a simple debounce on an element input event like so:

Observable
        .fromEvent(this.elInput.nativeElement, 'input')
        .debounceTime(2000)
        .subscribe(event => this.onInput(event));

我想根据事件在发出时的值来设置防抖条件,这有可能吗?

I would like to make the debounce conditional based on the value of the event when emitted, is this possible?

谢谢

推荐答案

是的,这是完全可能的.只需使用debounce运算符而不是debounceTime.传递给选择器函数,该函数在调用时会收到先前的运算符通知.

Yes, that's completely possible. Just make use of the debounce operator instead of debounceTime. It is passed a selector function that receives the previous operators notifaction when invoked.

在您的示例中:

Observable
        .fromEvent(this.elInput.nativeElement, 'input')
        .debounce(ev => ev.hasSomeValue ? timer(2000) : EMPTY)
        .subscribe(event => this.onInput(event));

选择器函数需要一个ObservableLike并等待其发出,然后转发debounce收到的最后一个通知.与debounceTime一样,所有其他通知都将被丢弃.您可以使用EMPTY立即转发通知,而不会发生任何超时(尽管这将是异步的,请参见下文)

The selector function expects an ObservableLike and waits for it to emit before forwarding the last notification that debounce received. All other notifications are discarded, like with debounceTime. You can use EMPTY to immediately forward the notifcation without any timeout (though this will be async, see below)

来自学习rxjs :

尽管反跳时间没有广泛使用,但是当反跳速率可变时,反跳很重要!

Though not as widely used as debounceTime, debounce is important when the debounce rate is variable!

注意:即使内部Observable立刻发出信号,防抖动也会始终异步安排最后一个值的转发.为避免这种情况,您必须创建第二个可观察对象,并使用filter完全避免使用debounce.

Note: Debounce will always asynchronously schedule the forwarding of the last value, even if the inner Observable emits instantly. To avoid this, you'd have to create a second observable and use filter to avoid debounce altogether.

这篇关于如何使可观察到的反跳时间成为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆