apreg apreg - 1 year ago 324
Javascript Question

Implement delayed queue with RxJs Observable

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.
enter image description here

Here is the code based on Dorus's answer

Answer Source

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 next item
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download