本文介绍了如何将Android Task转换为Kotlin Deferred?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Firebase匿名登录返回任务(基本上是 Google承诺实现):
Firebase anonymous sign in returns a task (which is basically Google promise implementation):
val task:Task<AuthResult> = FirebaseAuth.getInstance().signInAnonymously()
如何创建signInAnonymous
包装器,其中:
How it would be possible create a signInAnonymous
wrapper where:
-
这是一个
suspend
函数,等待task
完成
-
suspend fun signInAnonymous(): Unit
它返回一个Deferred
对象,异步传递结果
It returns a Deferred
object, delivering the result asynchronously
-
fun signInAnonymous() : Deferred
推荐答案
基于此GitHub库,这是一种将Task
转换为通常"的方式基于回调的协程异步调用:
Based on this GitHub library, here's a way to transform a Task
into a suspending function in the "usual" way to adapt callback based async calls to coroutines:
suspend fun <T> Task<T>.await(): T = suspendCoroutine { continuation ->
addOnCompleteListener { task ->
if (task.isSuccessful) {
continuation.resume(task.result)
} else {
continuation.resumeWithException(task.exception ?: RuntimeException("Unknown task exception"))
}
}
}
您当然也可以将其包装在Deferred
中,在这里CompletableDeferred
会派上用场:
You can also wrap it in a Deferred
of course, CompletableDeferred
comes in handy here:
fun <T> Task<T>.asDeferred(): Deferred<T> {
val deferred = CompletableDeferred<T>()
deferred.invokeOnCompletion {
if (deferred.isCancelled) {
// optional, handle coroutine cancellation however you'd like here
}
}
this.addOnSuccessListener { result -> deferred.complete(result) }
this.addOnFailureListener { exception -> deferred.completeExceptionally(exception) }
return deferred
}
这篇关于如何将Android Task转换为Kotlin Deferred?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!