使用RxJs Observable实现延迟队列 [英] Implement delayed queue with RxJs Observable

查看:1162
本文介绍了使用RxJs Observable实现延迟队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我们有一个布尔值队列(我们不需要复杂的数据结构,因为我们只想存储订单的事实).物品可以随时随地进入队列. Observable将从此队列中弹出项目,并以延迟的方式发出它们,但不需要延迟第一次发出.队列变空后,它将保持等待状态,直到有新项目进入队列并立即发出.请帮助我实现此行为.

鉴于用户可以按下使计数器递增的按钮.开始时,计数器为0,用户在500毫秒内单击两次.第一次单击会将计数器增加到一个,但第二次单击将采取延迟500 ms的操作.然后,用户等待超过500毫秒并单击.可以说,第三次单击必须立即增加计数器,因为没有其他正在进行的增加操作.如果第三次单击发生在500 ms窗口中,则它必须等到其他操作完成.

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.

是的,我想我的问题是@estus.不知何故,有必要记录其进展中的最后一个动作在哪里.节省发射时间或其他时间.

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.

鉴于第一次点击发生在300毫秒之前,并且发生了一次新点击.在这种情况下,第二次点击仅需等待200毫秒.

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

更新1: 此处是基于Dorus答案的代码

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

推荐答案

您可以使用

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
  )

这篇关于使用RxJs Observable实现延迟队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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