RxJS油门行为;立即获得第一个价值 [英] RxJS throttle behavior; get first value immediately

查看:106
本文介绍了RxJS油门行为;立即获得第一个价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例Plunkr: https://plnkr.co/edit/NZwb3ol8CbZFtSc6Q9zm?p=preview

我知道rxjs有这3种限制方法(5.0 beta.4):

I am aware that there are these 3 throttle methods for rxjs (5.0 beta.4):

auditTime() throttleTime() debounceTime()

我正在寻找的行为是lodash默认在油门上执行的行为:

The behavior I am looking for is the one lodash does by default on throttle:


  • 1)立即给我第一个值!

  • 2)连续值,保持给定延迟的值,然后发出最后一个值

  • 3)当油门延迟到期时,返回状态(1)

理论上这应该是这样的:

In theory this should look like:

inputObservable
  .do(() => cancelPreviousRequest())
  .throttleTime(500)
  .subscribe((value) => doNextRequest(value))

但是


  • throttleTime 永远不会给我最后一个值,如果在油门超时中发出

  • debounceTime 不会立即触发

  • auditTime 不会立即触发

  • throttleTime never gives me the last value, if emitted in the throttle timeout
  • debounceTime doesn't trigger immediately
  • auditTime doesn't trigger immediately

我可以组合任何rxjs方法来实现所描述的行为吗?

Could I combine any of the rxjs methods to achieve the described behavior?

推荐答案

我拿了auditTime运算符并更改了2行实现理想的行为。

I took the auditTime operator and changed 2 lines to achieve the desired behavior.

新的plunker: https://plnkr.co/edit/4NkXsOeJOSrLUP9WEtp0?p=preview

New plunker: https://plnkr.co/edit/4NkXsOeJOSrLUP9WEtp0?p=preview

原文:

  • https://github.com/ReactiveX/rxjs/blob/master/src/operator/auditTime.ts

更改:

protected _next(value: T): void {
  this.value = value;
  this.hasValue = true;
  if (!this.throttled) {
    this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, this));
  }
}

clearThrottle(): void {
  const { value, hasValue, throttled } = this;
  if (throttled) {
    this.remove(throttled);
    this.throttled = null;
    throttled.unsubscribe();
  }
  if (hasValue) {
    this.value = null;
    this.hasValue = false;
    this.destination.next(value);
  }
}

到(auditTimeImmediate):

to (auditTimeImmediate):

protected _next(value: T): void {
    this.value = value;
    this.hasValue = true;
    if (!this.throttled) {
        // change 1:
        this.clearThrottle();
    }
}

clearThrottle(): void {
    const { value, hasValue, throttled } = this;
    if (throttled) {
        this.remove(throttled);
        this.throttled = null;
        throttled.unsubscribe();
    }
    if (hasValue) {
        this.value = null;
        this.hasValue = false;
        this.destination.next(value);
        // change 2:
        this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, this));
    }
}

所以我在价值<$后开始超时c $ c> next ed。

用法:

inputObservable
  .do(() => cancelPreviousRequest())
  .auditTimeImmediate(500)
  .subscribe((value) => doNextRequest(value))

这篇关于RxJS油门行为;立即获得第一个价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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