Skip to content

Instantly share code, notes, and snippets.

@SUPERCILEX
Created March 27, 2018 06:02
Show Gist options
  • Save SUPERCILEX/29c42ca84a716042ca27c60135206cfd to your computer and use it in GitHub Desktop.
Save SUPERCILEX/29c42ca84a716042ca27c60135206cfd to your computer and use it in GitHub Desktop.
Google Play Services Tasks API with Kotlin Coroutines support
suspend fun <T> Task<T>.await(): T {
if (isComplete) return if (isSuccessful) result else throw exception!!
return suspendCoroutine { c: Continuation<T> ->
addOnSuccessListener { c.resume(it) }
addOnFailureListener { c.resumeWithException(it) }
}
}
fun <T> Deferred<T>.asTask(): Task<T> {
val source = TaskCompletionSource<T>()
invokeOnCompletion {
try {
source.setResult(getCompleted())
} catch (e: Exception) {
source.setException(e)
}
}
return source.task
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment