我们正在进行一些原型(prototype)测试,我们通过 http 获取包含大约 28000 条记录的 json。我们将其转换为 Typescript 中的类实例,并将其添加到现有数组中。
然后将数组绑定(bind)到重新显示列表的 View 。
this.http.get("http://localhost:8100/list.son")
.map((res) => res.json())
.flatMap((array, index) => array).
.subscribe((value:any) => {
console.log("RENDERING");
this.list.push(new Element(8, value.name, value.number));
});
问题在于,平面映射似乎将数组的元素一一同步地传递给订阅函数(尝试在仅在订阅之后运行的 http 调用之前使用设置的超时)。因此,它是一种 28000 个元素的循环,它挂起 UI 线程。我们如何才能定期触发订阅,以便 UI 线程在处理列表元素期间可以获得一些时间。 (本质上是伪异步递归)。
编辑:用 Meir 的答案更新了代码
这是我目前拥有的代码,另外我相信map是错误的操作,因为它输出它接受的输入数量。所以如果我错了请纠正我,它接受一个http响应并输出一个数组,并且因此,该数组将由其余步骤作为一个整体进行处理。此外,我还提供了示例 list.json。
this.http.get("http://localhost:8100/list.json")
.map((res) => {
console.log(res.json().list);
return res.json().list
})
.delayWhen((v) => Observable.timer(50))
.buffer(Observable.timer(50, 50))
.subscribe((entry) => {
console.log("CAME HERE AA " + entry);
});
LIST JSON,还有更多条目,但我在这里只保留了两个
{ "list" : [
{
"name" : "test",
"number" : "that",
"verificationId" : 78
},
{
"name" : "test",
"number" : "that",
"verificationId" : 78
},
{
"name" : "test",
"number" : "that",
"verificationId" : 78
},
{
"name" : "test",
"number" : "that",
"verificationId" : 78
}]
}
最佳答案
您可以按 block 大小或时间对其进行分块,时间 block 使用:
source.buffer(Rx.Observable.timer(250, 250))
.subscribe(chunk => {
console.log('chunk ', chunk);
list1.splice(list1.length, 0, ...chunk);
});
工作中jsbin sample两种情况都有。
关于javascript - RxJS异步循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40267496/