我有一个可观察对象,可以将 dragover
事件限制 350 毫秒,并返回 true
,只要这些事件不断出现:
Rx.Observable
.fromEvent(document, 'dragover')
.map(function () { return true; })
.throttle(350)
.distinctUntilChanged()
我想知道过去 350 毫秒内是否没有发生拖拽事件,并在发生这种情况时返回 false
。我应该怎样做呢?
我是否需要有一个单独的计时器并在发生 dragover
事件时重置它?我希望我能保持这个无状态。
最佳答案
有一个名为 timeout
的运算符可以执行此操作。
Rx.Observable
.fromEvent(document, 'dragover')
.throttle(350)
.map(true)
.timeout(350, Rx.Observable.just(false))
.distinctUntilChanged();
请注意,timeout
将从源 Observable
取消订阅并使用您传入的订阅,因此您不会从该 获得任何进一步的结果可观察
直到您重新订阅它。
此外,我建议您将map
操作放在throttle
之后,以避免对您不会的值进行不必要的映射操作使用。
我建议考虑一下这些计时是否真的是您想要的,因为您限制了超过 350 毫秒,所以 350 毫秒的超时会留下一些相当狭窄的余地。 1/3 秒对于 react 来说并不是很多时间,尤其是对于用户而言。由于您已经有一个下游 distinctUntilChanged
,您甚至可能不需要限制,因为您只会在从 true 变为 false 时发出值。
编辑
如果您需要Observable
继续,您可以使用doWhile
或repeat
重新订阅(我在测试中使用了mousemove):
Rx.Observable.fromEvent(window, 'mousemove')
.map(true)
.timeout(1000, Rx.Observable.just(false))
.repeat()//.doWhile(function() { return true; })
.distinctUntilChanged()
.subscribe(function(value) { console.log(value); });
//Outputs
/* Mouse starts moving */
// true
/* Mouse stopped moving for 1 second */
// false
/* Mouse still not moving no emit */
/* Mouse starts moving again */
// true
关于rxjs - 如何检测可观察序列在一段时间后没有产生值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33108683/