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

标签 android firebase kotlin kotlinx.coroutines

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/

相关文章:

kotlin - 我可以使用 kotlin "also"函数来缩短代码吗?

javascript - 使用摄像头和 GPS 的 Android WebView

javascript - 如何从 Firebase 存储获取图像的下载 url?

Android Shark (tcpdump) 创建无效的 pcap

iOS Swift Firebase 登录/注册 View 弹出窗口

forms - 如何制作 Firebase 表单?

java - 卡夫卡只订阅最新消息?

string - 每 n 个字符拆分字符串

android - 在Android中如何将ListAdapter值传递给onItemClick?

java - 如何在 recyclerview 元素中设置固定的 CountDownTimer?