Skip to content

Instantly share code, notes, and snippets.

@mathew-kurian
Last active August 29, 2017 07:13
Show Gist options
  • Save mathew-kurian/2bd2b8b3a2f6438d6786 to your computer and use it in GitHub Desktop.
Save mathew-kurian/2bd2b8b3a2f6438d6786 to your computer and use it in GitHub Desktop.
Android setTimeout, clearTimeout
main() {
Object tid = Utils.setTimeout(() -> {
asyncTask.cancel();
}, 3000);
asynTask.onResult(() -> {
Utils.clearTimeout(tid);
})
}
public class Utils {
public static Object setTimeout(Runnable runnable, long delay) {
return new TimeoutEvent(runnable, delay);
}
public static void clearTimeout(Object timeoutEvent) {
if (timeoutEvent != null && timeoutEvent instanceof TimeoutEvent) {
((TimeoutEvent) timeoutEvent).cancelTimeout();
}
}
private static class TimeoutEvent {
private static Handler handler = new Handler();
private volatile Runnable runnable;
private TimeoutEvent(Runnable task, long delay) {
runnable = task;
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (runnable != null) {
runnable.run();
}
}
}, delay);
}
private void cancelTimeout() {
runnable = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment