【问题标题】:Stop interval when empty array空数组时的停止间隔
【发布时间】:2019-07-26 07:19:06
【问题描述】:

我从服务器端收到一堆消息,我想通过在管道中添加一个间隔来伪造打字。

我现在正在这样做:

const stream = interval(1000)
  .pipe(
  map((): Message => {
    return messages.pop();
  })
);

this.feed = merge(
  stream,
  this.local
).pipe(
  scan((acc, x) => [...acc, x], [])
);

但是我希望它在我的数组“消息”为空时停止间隔,有人可以帮我吗?我一直在尝试实施 .TakeWhile,但没有成功。

提前致谢。

【问题讨论】:

    标签: angular typescript kendo-ui rxjs conversational-ui


    【解决方案1】:

    takeWhile 工作正常,你需要这样的东西:

    const stream = interval(1000)   
      .pipe(
         takeWhile(() => messages.length > 0),
         map(() => messages.pop()),   
      );
    

    我在 stackblitz 上做了一个小例子,希望你能把它应用到你的应用程序中: https://stackblitz.com/edit/typescript-sq6wxb?file=index.ts

    【讨论】:

      【解决方案2】:

      所以你的问题是即使messages 为空,stream 也会继续发射。

      您可以使用takeWhile 完成直播:

      const stream = interval(1000).pipe(
        map((): Message => messages.pop()),
        takeWhile(Boolean),
      );
      

      messages 为空时,它返回undefined,当转换为布尔值时false,因此takeWhile(Boolean) 将完成流。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-19
        • 2016-06-20
        • 2019-09-08
        • 2013-05-02
        • 1970-01-01
        • 2019-10-04
        • 2019-02-16
        相关资源
        最近更新 更多