Last active
August 29, 2017 07:13
-
-
Save mathew-kurian/2bd2b8b3a2f6438d6786 to your computer and use it in GitHub Desktop.
Android setTimeout, clearTimeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
main() { | |
Object tid = Utils.setTimeout(() -> { | |
asyncTask.cancel(); | |
}, 3000); | |
asynTask.onResult(() -> { | |
Utils.clearTimeout(tid); | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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