Skip to content

Instantly share code, notes, and snippets.

@aleksandarzekovic
Last active September 14, 2022 06:23
Show Gist options
  • Save aleksandarzekovic/fb44be921b21371111d669bc01e4664f to your computer and use it in GitHub Desktop.
Save aleksandarzekovic/fb44be921b21371111d669bc01e4664f to your computer and use it in GitHub Desktop.
public suspend fun delay(timeMillis: Long) {
if (timeMillis <= 0) return // don't delay
return suspendCancellableCoroutine sc@ { cont: CancellableContinuation<Unit> ->
// if timeMillis == Long.MAX_VALUE then just wait forever like awaitCancellation, don't schedule.
if (timeMillis < Long.MAX_VALUE) {
cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont)
}
}
}
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) {
postDelayed(Runnable {
with(continuation) { resumeUndispatched(Unit) }
}, timeMillis)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment