问题描述
- 有一个函数可以从 应用程序,该对象将被传递一个对象。
- 我们需要做的是调用一个后端API,并将其标为Post
身体。 - 不过,我想做的是整理这些更新,以获取
间隔一段时间-然后将它们一起发送到
减少对后端的呼叫次数。
所以,我正在考虑将这些项目添加到数组 。使用此数组创建一个可观察的对象 并通过管道 bufferTime 将这些值缓冲特定的时间,然后再发出它们。
我创建了一个Stackblitz-https://stackblitz.com/edit/typescript-fzezep?file=index.ts&devtoolsheight=100 如果您看到输出- 输出前20个值,这些值是在订阅前添加的。 但是最后20个值永远不会发出。
解决方法
您在那做过的一个非常常见的rxjs错误。
所以首先让我们逐行介绍您的例子
// You create an empty array
const dataArray = [];
// You create an observable that will point to the created dataArray
const bufferBy = from(dataArray);
let myBufferedInterval;
// You fill the dataArray with 20 elements
for (var i = 0; i <= 20; i++) {
dataArray.push(i);
}
// You create an observable that has will have for it's source from(dataArray)
myBufferedInterval = bufferBy.pipe(bufferCount(5));
// You create a SUBSCRIPTION on myBufferInterval which will go upstream to the observable that points to the dataArray with 20 element and make everything alive
const buffered = myBufferedInterval.subscribe(val => console.log(val));
// Here you add more element to the dataArray,but they will not result with new values in your subscription as your subscription points to the instance of dataArray with 20 elements (so each subscribe makes a individual subscription pointing to it's own instance of the dataArray)
for (var i = 21; i < 40; i++) {
dataArray.push(i);
}
console.log(dataArray)
// If you create new subscriton here it will have as reference an array that holds 40 elements. so you will be able to see the rest of the numbers (20+)
myBufferedInterval.subscribe(val => console.log(val));
处理此问题的rxjs
方法类似于以下代码段。区别在于,使用支持方法array
的{{1}} rxjs
对象而不是Subject
im。
所以我要做的是为此next
创建一个subscriton
,将其通过Subject
向下输送,以便有5个元素批次,我开始等待缓冲区装满。
此后,每当我使用buffer
方法时,next
都会向其订阅者发出一个新值,在我们这种情况下,它将开始填充缓冲区。
Subject
let { from,interval,Subject } = rxjs;
let { bufferCount,bufferTime } = rxjs.operators;
const requestHolder = new Subject();
requestHolder.pipe(bufferCount(5)).subscribe(val => console.log(val));
for (var i = 0; i <= 10; i++) {
requestHolder.next(i);
}
for (var i = 11; i < 20; i++) {
requestHolder.next(i);
}