使用 RXJS 延迟每个元素 [英] Delay for every element with RXJS

查看:20
本文介绍了使用 RXJS 延迟每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RxViz 来模拟每 1 秒出现一次的不同动作.当我尝试

I'm using RxViz to simulate different actions that comes every 1 sec. When I try

Rx.Observable.create(obs => {
  obs.next([1, 2, 3]); // or could be ['aaa', 'bbbb', 'ccc']
  obs.complete();
}).delay(1000);

https://rxviz.com

或者我自己使用 console.log

or on my own with a console.log

它一直同时显示三个数字1、2、3

it keeps displaying the three number 1, 2, 3 at the same time

有一篇关于同样问题的帖子,但没有一个答案对我有用.我正在使用 Rx 最新版本 6

There's a post about this same problem, but none of the answer works for me. I'm using Rx last version 6

如何创建具有延迟的可观察对象

数组可以包含任何东西,如数字、字符串或任何对象

The array can contains anything like number, string or any object

推荐答案

如果您想延迟每个值(例如延迟 1 秒),您可以执行以下操作:

If you want to delay each value (by 1 sec for example), you may do something like the following:

 Rx.Observable.create(obs => {
      obs.next([1, 2, 3]);
      obs.complete();
    })
      .pipe(
        // make observable to emit each element of the array (not the whole array)
        mergeMap((x: [any]) => from(x)),
        // delay each element by 1 sec
        concatMap(x => of(x).pipe(delay(1000)))
      )
      .subscribe(x => console.log(x));
  }

这里我没有修改你创建的 observable 的内部结构.相反,我只是将您的 observable 应用适当的操作来实现您的预​​期.

Here I did not modify the internals of the observable created by you. Instead, I just take your observable and apply appropriate operations to achieve what you seem to be expecting.

这篇关于使用 RXJS 延迟每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆