【发布时间】:2011-01-20 00:10:10
【问题描述】:
对于我正在编写的一些代码,我可以在 Java 中使用 debounce 的一个很好的通用实现。
public interface Callback {
public void call(Object arg);
}
class Debouncer implements Callback {
public Debouncer(Callback c, int interval) { ... }
public void call(Object arg) {
// should forward calls with the same arguments to the callback c
// but batch multiple calls inside `interval` to a single one
}
}
当call() 在interval 毫秒内以相同的参数被多次调用时,回调函数应该只被调用一次。
可视化:
Debouncer#call xxx x xxxxxxx xxxxxxxxxxxxxxx
Callback#call x x x (interval is 2)
- 某些 Java 标准库中是否已经存在(类似的东西)?
- 您将如何实现它?
【问题讨论】:
-
看起来 java.util.concurrency 提供了构建块
-
我知道这是一个老问题,但几个月前我在这里发布了一个类似的问题:stackoverflow.com/questions/18723112/… 并在 GitHub 上提供了一个可能感兴趣的可重用实现