Produce a stream of values with data-driven delays in RxJS

末鹿安然 提交于 2020-01-05 04:15:06

问题


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

var data = [ { message:"Deliver me after 1000ms", time:1000 }, { message:"Deliver me after 2000ms", time:2000 }, { message:"Deliver me after 3000ms", time: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.

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.


回答1:


You could use 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>


来源:https://stackoverflow.com/questions/41608636/produce-a-stream-of-values-with-data-driven-delays-in-rxjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!