Skip to content

Instantly share code, notes, and snippets.

@Sefford
Last active August 29, 2015 14:14
Show Gist options
  • Save Sefford/79b3a56b844009e60431 to your computer and use it in GitHub Desktop.
Save Sefford/79b3a56b844009e60431 to your computer and use it in GitHub Desktop.
Debouncer class will allow to avoid fast clicking into views
import android.support.v4.util.LongSparseArray;
import javax.inject.Inject;
/**
* Debouncer class will allow to avoid fast clicking into views
*
* @author Saul Diaz
*/
public class Debouncer {
/**
* Debouncing threshold
*/
static final long DEBOUNCING_THRESHOLD = 1000;
/**
* Debouncing SparseArray for absorbing the debouncing threshold
* by Anderwebs
*/
final LongSparseArray<Long> debouncingMap;
/**
* Time provider to obtain when the clicks are done
*/
TimeProvider timeProvider;
/**
* Creates a new instance of the Debouncer
*
* @param timeProvider
*/
@Inject
public Debouncer(TimeProvider timeProvider) {
this.timeProvider = timeProvider;
debouncingMap = new LongSparseArray<>();
}
/**
* Absorbs the bouncing of fast clicking
*
* @param id id of the View
* @return TRUE if it is first bounce, false for possible rebounds
*/
public boolean debounce(int id) {
long time = timeProvider.getCurrentTimeMillis();
boolean result = !(debouncingMap.indexOfKey(id) > -1 && (time - debouncingMap.get(id) < DEBOUNCING_THRESHOLD));
debouncingMap.put(id, time);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment