【问题标题】:RxJS emit array of strings, one second apart from each otherRxJS 发出字符串数组,彼此相隔一秒
【发布时间】:2021-09-13 19:20:42
【问题描述】:

我有一段代码负责获取 Observable<string[]>,然后将其映射到 Observable<string> 并以 1 秒的间隔发出值。

可以把它想象成网站上的消息代码。

我当前的代码在下面工作:

    const arrayOfStrings$ = of([
        'Warming things up',
        'Getting things ready',
        'Welcome'
    ]);

    this.messages$ = arrayOfStrings$.pipe(
        switchMap((messages) => from(messages).pipe(
            concatMap((innerMessage) => of(innerMessage).pipe(delay(1000))),
        )),
        tap((message) => {
            console.log(`Message: ${message}`);
        })
    );

有没有更好的方法来用更少的代码做到这一点?困扰我的主要是 switchMap()concatMap() 在彼此内部。

感谢您的任何帮助和建议。

编辑:这是我在实际项目中运行的简化版本。我只是想找到一种更简单的方法来从 Observable 到 Observable 并在每次发射后将每次发射延迟一秒

【问题讨论】:

标签: javascript angular typescript rxjs


【解决方案1】:

您可以先展平数组,然后使用 concatMap() 延迟每个发射,这将确保消息一个接一个地发射。

const arrayOfStrings$ = of([
  'Warming things up',
  'Getting things ready',
  'Welcome'
]);

arrayOfStrings$
  .pipe(
    concatAll(), // flatten the array into individual next notifications
    concatMap(message => of(message).pipe(
      delay(1000),
    )),
  )
  .subscribe();

【讨论】:

  • 谢谢!这确实使代码更具可读性!
【解决方案2】:
of('one', 'two', 'three')
  .pipe(zipWith(interval(1000)))
  .subscribe(console.log)

或者如果你想立即开始替换间隔

timer(0, 1000)

【讨论】:

    【解决方案3】:

    我会使用以下代码:

    const arrayOfStrings$ = of([
      'Warming things up',
      'Getting things ready',
      'Welcome'
    ]);
    
    arrayOfStrings$.pipe(
      mergeMap((a) => a),
      zip(timer(1000, 1000)),
      map(([a]) => a),
      tap(message => {
        console.log(`Message: ${message}`);
      })
    );
    

    【讨论】:

    • 感谢您拍摄。在我使用的 rxjs 版本(v6)中,fromArray() 被弃用,取而代之的是 from()。我无法更改 arrayOfStrings$ 的值,因为在我的项目代码中,它连接到主题 的输出。省略了那个细节,因为我想简化问题。我从 Observable 开始,我想以 Observable 间隔 1 秒结束
    • @DamianC 我更新了我的代码以使用arrayOfStrings$ 的原始定义。带有标识函数的mergeMap解包主题的字符串。
    猜你喜欢
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    相关资源
    最近更新 更多