implementing debounce in Java

前端 未结 8 657
心在旅途
心在旅途 2020-11-30 04:09

For some code I\'m writing I could use a nice general implementation of debounce in Java.

public interface Callback {
  public void call(Object          


        
8条回答
  •  一向
    一向 (楼主)
    2020-11-30 04:47

    The following implementation works on Handler based threads (e.g. the main UI thread, or in an IntentService). It expects only to be called from the thread on which it is created, and it will also run it's action on this thread.

    public class Debouncer
    {
        private CountDownTimer debounceTimer;
        private Runnable pendingRunnable;
    
        public Debouncer() {
    
        }
    
        public void debounce(Runnable runnable, long delayMs) {
            pendingRunnable = runnable;
            cancelTimer();
            startTimer(delayMs);
        }
    
        public void cancel() {
            cancelTimer();
            pendingRunnable = null;
        }
    
        private void startTimer(final long updateIntervalMs) {
    
            if (updateIntervalMs > 0) {
    
                // Debounce timer
                debounceTimer = new CountDownTimer(updateIntervalMs, updateIntervalMs) {
    
                    @Override
                    public void onTick(long millisUntilFinished) {
                        // Do nothing
                    }
    
                    @Override
                    public void onFinish() {
                        execute();
                    }
                };
                debounceTimer.start();
            }
            else {
    
                // Do immediately
                execute();
            }
        }
    
        private void cancelTimer() {
            if (debounceTimer != null) {
                debounceTimer.cancel();
                debounceTimer = null;
            }
        }
    
        private void execute() {
            if (pendingRunnable != null) {
                pendingRunnable.run();
                pendingRunnable = null;
            }
        }
    }
    

提交回复
热议问题