首页 文章

RxJS异步循环

提问于
浏览
0

我们正在进行一些原型测试,我们采用json,通过http获得大约28000条记录 . 我们将它转换为Typescript中的类的实例,并将其添加到现有数组中 .

然后,该数组将绑定到视图,该视图将显示该列表 .

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));
                  });

问题是flatmap似乎是将数组的元素一个接一个地传递给subscribe函数(尝试在http调用之前使用set timeout,它只在订阅之后运行) . 因此,它是一种28000个元素的循环,它挂起了UI线程 . 我们如何在间隔的基础上触发订阅,以便UI线程可以在处理列表元素期间获得一些时间 . (基本上是伪异步递归) .

EDIT : Updated code with Meir's answer

这是我目前的代码,另外我认为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);
                });

列表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
  }]
}

1 回答

  • 1

    您可以按块大小或时间对其进行分块,以便时间块使用:

    source.buffer(Rx.Observable.timer(250, 250))
       .subscribe(chunk => {
         console.log('chunk ', chunk);
         list1.splice(list1.length, 0, ...chunk);
    });
    

    一个工作jsbin sample与两个案件 .

相关问题