如何使用RxJS实现以下内容?
A-B-C-d-E-F-G-H
ab --- cd --- ef --- gh
或
A-B-C-d-E-F-G-H
ABC DEF ---- ---- GH
我有一个数组,我需要按指定的分区拆分并以指定的间隔发出值。
答案 0 :(得分:4)
请注意,你不能从'a-b-'获得'ab--'因为你必须等待'b',所以严格来说大理石图将是
a-b-c-d-e-f-g-h-|
-(ab)---(cd)---(ef)---(gh|)
or
a-b-c-d-e-f-g-h-|
--(abc)----(def)----(gh|)
console.clear()
const Observable = Rx.Observable
const timedEmitter = (observable, interval) =>
Observable.zip(observable, Observable.timer(0, interval))
.map(x => x[0])
const source = Observable.from(['a','b','c','d','e','f','g','h'])
const timedSource = timedEmitter(source, 1000)
const interval = 5000
const size = 3
const output = timedEmitter(timedSource.bufferCount(size), interval)
//Display
const start = new Date()
output.timestamp()
.map(x => { return {value: x.value, elapsed: x.timestamp - start} })
.subscribe(console.log)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>
脚注,在timedEmitter中将Observable.interval(interval)
更改为Observable.timer(0, interval)
以获得第一个尽快发出。
脚注#2 ,这不太正确,因为来源的 complete()
会使最后一个间隔短路。
这只是所选间隔的一件神器。
以下是使用来自RxJs 5.5的pipe()
的自定义运算符版本,参考Build your own operators easily
console.clear()
const Observable = Rx.Observable
const timedEmitter = (observable, interval) =>
Observable.zip(observable, Observable.timer(0, interval))
.map(x => x[0])
const source = Observable.from(['a','b','c','d','e','f','g','h'])
const timedSource = timedEmitter(source, 1000)
// Custom operator
const timedBufferedEmitter = (interval, bufferSize) => (observable) =>
Observable.zip(observable.bufferCount(bufferSize), Observable.timer(0, interval))
.map(x => x[0])
const interval = 5000
const size = 3
const output = timedSource.pipe(timedBufferedEmitter(interval, size))
//Display
const start = new Date()
output.timestamp()
.map(x => { return {value: x.value, elapsed: x.timestamp - start} })
.subscribe(console.log)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>