示例Plunkr:
https://plnkr.co/edit/NZwb3ol8CbZFtSc6Q9zm?p=preview
我知道rxjs有这3种节流方法(5.0 beta.4):
auditTime(),throttleTime()和debounceTime()
我正在寻找的行为是默认情况下lodash执行的一个节流:
> 1)马上给我第一个值!
> 2)在连续值上,保持给定延迟的值,然后发出最后出现的值
> 3)当油门延迟到期时,返回状态(1)
从理论上讲,这应该是这样的:
inputObservable .do(() => cancelPrevIoUsRequest()) .throttleTime(500) .subscribe((value) => doNextRequest(value))
但
>如果在节流超时中发出,> throttleTime永远不会给我最后一个值
> debounceTime不会立即触发
> auditTime不会立即触发
我可以结合任何rxjs方法来实现所描述的行为吗?
解决方法
对于较旧的RxJ,我编写了一个concatLatest运算符,它可以完成您想要的大部分操作.有了它,您可以使用以下代码获得限制行为:
const delay = Rx.Observable.empty().delay(500); inputObservable .map(value => Rx.Observable.of(value).concat(delay)) .concatLatest() .subscribe(...);
这是操作符.我尝试更新它以使用RxJS5:
Rx.Observable.prototype.concatLatest = function () { /// <summary> /// Concatenates an observable sequence of observable sequences,skipping sequences that arrive while the current sequence is being observed. /// If N new observables arrive while the current observable is being observed,the first N-1 new observables will be thrown /// away and only the Nth will be observed. /// </summary> /// <returns type="Rx.Observable"></returns> var source = this; return Rx.Observable.create(function (observer) { var latest,isStopped,isBusy,outerSubscription,innerSubscription,subscriptions = new Rx.Subscription(function () { if (outerSubscription) { outerSubscription.unsubscribe(); } if (innerSubscription) { innerSubscription.unsubscribe(); } }),onError = observer.error.bind(observer),onNext = observer.next.bind(observer),innerOnComplete = function () { var inner = latest; if (inner) { latest = undefined; if (innerSubscription) { innerSubscription.unsubscribe(); } innerSubscription = inner.subscribe(onNext,onError,innerOnComplete); } else { isBusy = false; if (isStopped) { observer.complete(); } } }; outerSubscription = source.subscribe(function (newInner) { if (isBusy) { latest = newInner; } else { isBusy = true; if (innerSubscription) { innerSubscription.unsubscribe(); } innerSubscription = newInner.subscribe(onNext,innerOnComplete); } },function () { isStopped = true; if (!isBusy) { observer.complete(); } }); return subscriptions; }); };
这是一个更新的plunkr:https://plnkr.co/edit/DSVmSPRijJwj9msefjRi?p=preview
注意我将您的lodash版本更新到最新版本.在lodash 4.7中,我重写了油门/去抖操作符来修复一些边缘案例错误.您使用的是4.6.1仍有一些错误,但我认为它们不会影响您的测试.