Firebase 匿名登录返回 task (基本上是 Google promise implementation ):
val task:Task<AuthResult> = FirebaseAuth.getInstance().signInAnonymously()
如何创建 signInAnonymous
包装器,其中:
是一个
suspend
函数,等待task
完成暂停有趣的signInAnonymous(): Unit
它返回一个
Deferred
对象,异步传递结果有趣的 signInAnonymous() : 延迟
最佳答案
包裹kotlinx.coroutines.tasks
现在包括以下实用功能:
public suspend fun <T> Task<T>.await(): T { ... }
来自 docs :
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 fun <T> Task<T>.asDeferred(): Deferred<T> { ... }
来自 docs :
Converts this task to an instance of Deferred.
If task is cancelled then resulting deferred will be cancelled as well.
所以你可以这样做:
suspend fun signInAnonymouslyAwait(): AuthResult {
return FirebaseAuth.getInstance().signInAnonymously().await()
}
或:
fun signInAnonymouslyDeferred(): Deferred<AuthResult> {
return FirebaseAuth.getInstance().signInAnonymously().asDeferred()
}
关于android - 如何将 Android 任务转换为 Kotlin Deferred?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50473637/