Implement delayed queue with RxJs Observable

人盡茶涼 提交于 2020-01-04 09:55:13

问题


Imagine we have a queue of booleans (we don't need a complex datastructure since we wanna store only the fact of the order). Items can get into the queue at anytime in any pace. The Observable would pop items from this queue and emit them in a delayed manner but the first emit is not needed to be delayed. After the queue gets empty it stay on hold until a new item gets in the queue which it will emmit right away. Please help me implement this behaviour.

Given a user can press a button which increments a counter. At start the counter is on 0 and the user clicks two times in 500 ms. The first click increments the counter to one but the second click will take action delayed by 500 ms. The user then waits more than 500 ms and clicks. The third click has to increment the counter right away since there is no other increment action in progress so to say. If the third click happens in the 500 ms window then it has to wait till the other finishes.

Yeah, I think I get your problem @estus. Somehow it would be neccessary to register where is the last action in its progress. Saving the time when it was emitted or something.

Given the first click has happened 300ms before and a new click happens. In this case the 2nd click has to wait only 200ms.

Update1: Here is the code based on Dorus's answer


回答1:


You can use concatMap:

delay = 1000; // delay in ms
queue.concatMap(e =>
    Rx.Observable.of(e) // emit first item right away
      .concat(Rx.Observable.empty().delay(delay)) // delay next item
  )


来源:https://stackoverflow.com/questions/40087269/implement-delayed-queue-with-rxjs-observable

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