Skip to content

Instantly share code, notes, and snippets.

@vyo
Created December 17, 2016 14:32
Show Gist options
  • Save vyo/85471a44783ee4ad183716bf47d43b9b to your computer and use it in GitHub Desktop.
Save vyo/85471a44783ee4ad183716bf47d43b9b to your computer and use it in GitHub Desktop.
Limit Kovenant promise by execution time
/**
* puts a time limit on the given [Promise]
* make sure to specify [Promise.fail] and/or [Promise.always] to be aware of the
* cancellation and be able to react accordingly
*
* @throws [IllegalArgumentException] if the given timeout is negative
*/
fun timedPromise(promise: Promise<Any, Exception>, millis: Long) {
if (millis < 0) {
throw IllegalArgumentException("Duration may not be negative: $millis")
}
//first promise wins, leading to the other being cancelled
any(listOf(promise, task { Thread.sleep(millis) }))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment