Rx.js It’s about time you used RxJS
1.Timing
- RxJS allows you greater control in manipulating and tracking the flow of time in an application.
在追踪和操控应用时间流上,RxJS提供了强大的控制
Operators can interact with time to change the output of an observable.
Operator可以随时通过时间,改变observable的输出
Time can be implicit, or it can be explicitly declared when more fine-grained control is needed.
时间可以是隐式的,当需要更细致的控制时,时间也可以是显示的
Implicit time manifests in the latency waiting for asynchronous HTTP calls to respond. You have no control over how long these functions take.
隐式体现在,等待异步HTTP请求,这个时间是无法控制的
1.Implicit timing
隐式时间
2.Explicit timing
显示时间
2
1.SetTimeout
Rx.Observable.timer(1000)
.subscribe(()=>
document.querySelector('#panel').style.backgroundColor = 'red');
2.2.Interval
.skip(1)
.take(5)
.map(num => new USDMoney(newRandomNumber()))
// WARNING: NOT IN TEXT
// Added to address #11 (https://github.com/RxJSInAction/rxjs-in-action/issues/11)
.map(usd => usd.toString())
.forEach(console.log);
2.3.Delay
.delay(2000)
.timeInterval()
.map(int => Math.floor(int.interval / 1000))
.subscribe(seconds => console.log(`${seconds} seconds`));
3.Handling user input
Delaying shifts the observable sequence by a due time (in milliseconds).
可以根据时间延迟
Debouncing emits an event from an observable sequence only after a particular
time span (in milliseconds) has passed without it omitting any other item.
去抖,触发observale在一段时间之后发生的时间,会忽略其他的
Throttling enforces a maximum number of times a function can be called over
time.
节流,一段时间触发一次
Buffering operations use many of the same semantics as the timing operations.
buffer用许多相同语义,作为timing opertator
RxJS features size-based as well as time-based buffers.
size-based 和 time-base缓存 一样
1.Debouncing
let debouncedRequest = debounce(sendRequest, 1000);
searchBox.addEventListener('keyup', function (event) {
debouncedRequest(event.target.value);
});
2.Throttling
Rx.Observable.fromEvent(document, 'mousemove')
.throttleTime(2000)
.subscribe(event => {
console.log(`Mouse at: ${event.x} and ${event.y}`);
});
3.Buffering
buffer
bufferTime
bufferToggle
bufferWhen
Rx.Observable.fromEvent(field, 'keyup')
.debounceTime(700)
.pluck('target', 'value')
.filter(R.compose(R.not, R.isEmpty)) //#A
.bufferWhen(() => showHistory$) //#B
.do(history => history.pop())
.subscribe(history => {
let contents = '';
if(history.length > 0) { //#C
for(let item of history) {
contents += '<li>' + item + '</li>';
}
historyPanel.innerHTML = contents;
}
});