我想缓冲流,直到流的谓词为真:
例如,数字可以除以五:
//emit value every 1 second
const oneSecondInterval = Rx.Observable.interval(1000);
//return an observable that checks if the number is divided by zero
const fiveSecondInterval = () => oneSecondInterval.filter(number => number % 5 === 0);
const bufferWhenExample = oneSecondInterval.bufferWhen(fiveSecondInterval);
//log values
const subscribe = bufferWhenExample.subscribe(val => console.log('Emitted Buffer: ', val));
输出
"Emitted Buffer: "
[]
"Emitted Buffer: "
[0, 1]
"Emitted Buffer: "
[2]
"Emitted Buffer: "
[3]
"Emitted Buffer: "
[4]
"Emitted Buffer: "
[5]
"Emitted Buffer: "
[6]
"Emitted Buffer: "
[7]
"Emitted Buffer: "
[8]
"Emitted Buffer: "
[9]
"Emitted Buffer: "
[10]
我想要什么:
"Emitted Buffer: "
[0]
"Emitted Buffer: "
[1,2,3,4,5]
"Emitted Buffer: "
[6,7,8,9,10]
但这不起作用。为什么?
演示:http://jsbin.com/durerimiju/1/edit?js,console
<小时/>更新
这已经差不多了
const oneSecondInterval = Rx.Observable.interval(1000);
const fiveSecondInterval = oneSecondInterval.filter(time => time % 5 === 0);
const bufferWhenExample = oneSecondInterval.buffer(fiveSecondInterval);
bufferWhenExample.subscribe(console.log)
唯一的问题是它会发射
[]
[0,1,2,3,4]
[5,6,7,8,9]
相反,我想要
[0]
[1,2,3,4,5]
[6,7,8,9,10]
最佳答案
这是似乎对我有用的解决方案(在 Typescript 中):
import { interval, OperatorFunction } from 'rxjs';
import { buffer, delay, filter, share, tap } from 'rxjs/operators';
export function bufferUntil<T>(predicate:(value:T) => boolean):OperatorFunction<T, T[]>
{
return function(source)
{
const share$ = source.pipe(share());
const until$ = share$.pipe(filter(predicate), delay(0));
return share$.pipe(buffer(until$));
};
}
interval(1000).pipe(
tap(console.log),
bufferUntil(value => value % 5 === 0),
tap(console.log)
).subscribe();
这会产生以下输出:
0
[0] // this emits immediately after the previous log
1
2
3
4
5
[1, 2, 3, 4, 5] // this emits immediately after the previous log
6
7
8
9
10
[6, 7, 8, 9, 10] // this emits immediately after the previous log
如果有人有更好的解决方案,或者我的实现在某种程度上是危险的或不正确的,我很乐意听到它,因为我自己需要此功能。
关于javascript - RxJS 缓冲区直到流为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760805/