【问题标题】:Avoiding nesting Observables ( mergeMap on complete )避免嵌套 Observables(完成时的 mergeMap)
【发布时间】:2021-11-11 15:52:37
【问题描述】:

得到这个抓取服务的伪代码,它首先探索分页网址,然后是抓取的“父”网站上的子页面网址

const pagination = [["url-1", "url-2", "url-3", "url-4"], ["url-5"]];
const timeInterval = 2;

sendRequestsInIntervals(pagination, timeInterval )
  .pipe()
  .subscribe({
    next(x) {
      console.log(x);
    },
    error(err) {
      console.error(err);
    },
    complete() {
      console.log("done");
      sendRequestsInIntervals(resDataArray, timeInterval ).subscribe({
        next(x) {
          console.log(x);
        },
      });
    },
  });

我想避免嵌套,因为它是使用 observables 的不正确方式

有没有办法把它转换成这样的东西:

sendRequestsInIntervals(pagination, timeInterval )
  .pipe(
    waitUntilCompletes()
    mergeMap((resDataArray) => {
      return sendRequestsInIntervals(resDataArray, timeInterval );
    })
  )
  .subscribe({
    next(x) {
      console.log(x);
    },
    error(err) {
      console.error(err);
    },
    complete() {
      console.log("done");
    },
  });

添加了一个名为 waitUntilCompletes()

的伪函数

在 rxJS 中是否有这样的事情,它让 mergeMap 中的 observable 在运行之前等待,直到前一个 observable 完成?

【问题讨论】:

  • toArray() 等待源观测完成。
  • 我使用了这种方法,谢谢提示

标签: javascript rxjs observable mergemap


【解决方案1】:

last 运算符将忽略所有排放,直到完成后的最后一个排放:

sendRequestsInIntervals(pagination, timeInterval )
  .pipe(
    last(),
    mergeMap((resDataArray) => { // resDataArray is only the final emitted value from sendRequestsInIntervals() 
      return sendRequestsInIntervals(resDataArray, timeInterval );
    })
  )
  .subscribe({
    next(x) {
      console.log(x);
    },
    error(err) {
      console.error(err);
    },
    complete() {
      console.log("done");
    },
  });

或者您可以使用reduce 收集排放并在完成后排放:

sendRequestsInIntervals(pagination, timeInterval )
  .pipe(
    // this will gather all outter emissions into an array and emit once outter completes
    reduce((acc, val) => acc.concat(val), []),
    mergeMap((resDataArray) => { // resDataArray is all values emitted from sendRequestsInIntervals() in an array
      return sendRequestsInIntervals(resDataArray, timeInterval );
    })
  )
  .subscribe({
    next(x) {
      console.log(x);
    },
    error(err) {
      console.error(err);
    },
    complete() {
      console.log("done");
    },
  });

【讨论】:

  • 我仍然需要其他排放的值,而不仅仅是最后一个。我可以做一个解决方法并在“sendRequestsInIntervals”中使用 array.push 以便最后一个包含所有内容,但我仍然想知道这是最接近这个想法的可用选项吗?
  • 我意识到我不能做数组推送,所以我必须想出一个更好的解决方案
  • 使用reduce收集中间排放物并在完成后排放
猜你喜欢
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 2018-06-03
  • 2020-11-26
  • 1970-01-01
  • 2011-02-16
  • 2016-11-19
相关资源
最近更新 更多