在 RxJS 中生成具有数据驱动延迟的值流 [英] Produce a stream of values with data-driven delays in RxJS

查看:36
本文介绍了在 RxJS 中生成具有数据驱动延迟的值流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个包含消息有效负载和时间参数的对象数组,如下所示:

Given an array of objects which contain a message payload and time parameter like this:

var 数据 = [{ message:"1000ms 后交付我", time:1000 },{ message:"2000ms 后交付我", time:2000 },{ 消息:3000 毫秒后交付我",时间:3000 }];

我想创建一个可观察序列,它返回数组每个元素的消息部分,然后等待对象中指定的相应时间量.如果有必要,我愿意重新组织数组的数据结构.

I would like to create an observable sequence which returns the message part of each element of the array and then waits for the corresponding amount of time specified in the object. I'm open to reorganising the data structure of the array if that is necessary.

我见过 Observable.delay,但不知道如何以这种方式将其与动态值一起使用.我在 RxJS 5 中工作.

I've seen Observable.delay but can't see how it could be used with a dynamic value in this way. I'm working in RxJS 5.

推荐答案

你可以使用 delayWhen:

var data = [
    { message:"Deliver me after 1000ms", time:1000 },
    { message:"Deliver me after 2000ms", time:2000 },
    { message:"Deliver me after 3000ms", time:3000 }
];

Rx.Observable
  .from(data)
  .delayWhen(datum => Rx.Observable.timer(datum.time))
  .do(datum => console.log(datum.message))
  .subscribe();

<script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/Rx.js"></script>

这篇关于在 RxJS 中生成具有数据驱动延迟的值流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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