Firebase anonymous sign in returns a task (which is basically Google promise implementation):

val task:Task<AuthResult> = FirebaseAuth.getInstance().signInAnonymously()

How it would be possible create a signInAnonymous wrapper where:

  • 这是一个suspend函数,等待task完成

  • 它返回一个Deferred对象,异步传递结果

    • fun signInAnonymous() : Deferred

推荐答案

The package kotlinx.coroutines.tasks now includes the follwing utility functions:

public suspend fun <T> Task<T>.await(): T { ... }

From the docs:

等待任务完成而不阻塞线程

public fun <T> Task<T>.asDeferred(): Deferred<T> { ... }

From the docs:

Converts this task to an instance of Deferred.
If task is cancelled then resulting deferred will be cancelled as well.


So you can just do:

suspend fun signInAnonymouslyAwait(): AuthResult {
    return FirebaseAuth.getInstance().signInAnonymously().await()
}

or:

fun signInAnonymouslyDeferred(): Deferred<AuthResult> {
    return FirebaseAuth.getInstance().signInAnonymously().asDeferred()
}

Kotlin相关问答推荐

在Webflux应用程序中通过kotlin协程启动fire and forget job

为何Kotlin标准库中的AND和OR函数不能像&&和||一样进行短路运算?

内容更改后的 var 重新计算

Kotlin 列表扩展功能

Jetpack Compose - 单击 LazyColumn 的项目时应用程序崩溃

Kotlin:伴随对象内的函数扩展

从 Kotlin 调用 Java 时可以为空的规则是什么

是否可以通过超时暂停协程?

Kotlin 枚举中的循环引用

如何设置两列recyclerview?

在java代码中使用kotlin库

Kotlin中的测试无法访问受保护(protected)的方法

kotlin 委托有什么用?

在android的默认浏览器 Select 列表中添加我的浏览器?

不推荐使用仅限生命周期的LifecycleEvent

将字符串转换为HashMap的最简单方法

将 androidx.constraintlayout:constraintlayout lib 更新到 2.0.2 版本后出现崩溃 isRtl () null 引用

访问Kotlin中的属性委托

用 kotlin 学习 Android MVVM 架构组件

函数引用和lambdas