当我触发此代码时:
timer(1000).pipe( expand(() => of('a')), take(3) ) .subscribe(data => alert(data));
我收到3次警报:警报为0,警报为'a',警报为'a'。我只想通过数组[0,a,a]收到一个警报。如何合并所有值?
您可以尝试使用RxJS scan和scan运算符。
scan
filter
这看起来是一个非常具体的用例。另请注意,可观察对象正在发出3条通知:filter,timer(1000).pipe( expand(() => of('a')), take(3), scan((acc, curr) => { acc.push(curr); return acc; }, []), filter(values => values.length === 3) ).subscribe(data => alert(data)); 和[0]。我们明确限制仅发出最后一个通知,因为我们知道它的长度应为3(由于[C0])。
timer(1000).pipe( expand(() => of('a')), take(3), scan((acc, curr) => { acc.push(curr); return acc; }, []), filter(values => values.length === 3) ).subscribe(data => alert(data));
[0]