There are various ways to schedule a delayed task in Android - How to call a method after a delay in Android
In our use case, during a long scrolling process, we would like to schedule delayed task along the way.
Since the scrolling event will be triggered multiple times, and delayed task will be scheduled multiple times as well.
However, we would like only the last scheduled task being executed. The rest of the prior scheduled tasks should be ignored/ cancelled.
Currently, this is our implementation.
private class OnScrollListener extends RecyclerView.OnScrollListener {
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
...
Timer oldTimer = this.timer;
if (oldTimer != null) {
oldTimer.cancel();
}
this.timer = new Timer();
this.timer.schedule(new MyTimerTask(), 3000);
}
Since there is multiple memory allocation/ de-allocation along the scrolling, it might cause our scrolling process less smooth.
I was wondering, is there a more runtime efficient way, to schedule multiple delayed tasks and ensuring only the last one is executed?