Java延迟执行(去抖动debounce)

2020-12-21 314点热度 0人点赞 0条评论

开发搜索功能的时候,需要根据用户实时输入的关键词进行搜索,但是用户快速输入每一个单词,就触发一次服务器请求,有点浪费资源,且体验不好,做法是等待用户比如500ms后,再进行搜索请求,直接上代码:

新建一个类:Debouncer.java
public class Debouncer {
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private final ConcurrentHashMap<Object, Future<?>> delayedMap = new ConcurrentHashMap<>();

    /**
     * Debounces {@code callable} by {@code delay}, i.e., schedules it to be executed after {@code delay},
     * or cancels its execution if the method is called with the same key within the {@code delay} again.
     */
    public void debounce(final Object key, final Runnable runnable, long delay, TimeUnit unit) {
        final Future<?> prev = delayedMap.put(key, scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {
                    delayedMap.remove(key);
                }
            }
        }, delay, unit));
        if (prev != null) {
            prev.cancel(true);
        }
    }

    public void shutdown() {
        scheduler.shutdownNow();
    }
}
调用方法
final Debouncer debouncer = new Debouncer();
debouncer.debounce(Void.class, new Runnable() {
    @Override public void run() {
        // ...
    }
}, 500, TimeUnit.MILLISECONDS);

Android版本,请看https://blog.terrynow.com/2020/12/22/android-debounce/

Swift版本,请看https://blog.terrynow.com/2020/12/22/ios-swift-debounce/

Javascript版本,请看https://blog.terrynow.com/2020/12/23/javascript-debounce/

admin

这个人很懒,什么都没留下

文章评论

*

code