gpt4 book ai didi

android - 如何将 Android 任务转换为 Kotlin Deferred?

转载 作者:IT老高 更新时间:2023-10-28 13:44:20 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com