Skip to content

Instantly share code, notes, and snippets.

@gastsail
Created December 21, 2019 15:45
Show Gist options
  • Save gastsail/298f5182877520be5135e218f1eec557 to your computer and use it in GitHub Desktop.
Save gastsail/298f5182877520be5135e218f1eec557 to your computer and use it in GitHub Desktop.
/**
* Awaits for completion of the task without blocking a thread.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function
* stops waiting for the completion stage and immediately resumes with [CancellationException].
*/
public suspend fun <T> Task<T>.await(): T {
// fast path
if (isComplete) {
val e = exception
return if (e == null) {
if (isCanceled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
result
}
} else {
throw e
}
}
return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
val e = exception
if (e == null) {
if (isCanceled) cont.cancel() else cont.resume(result)
} else {
cont.resumeWithException(e)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment