Created
December 21, 2019 15:45
-
-
Save gastsail/298f5182877520be5135e218f1eec557 to your computer and use it in GitHub Desktop.
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
/** | |
* 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