如何将 Android 任务转换为 Kotlin Deferred? [英] How to transform an Android Task to a Kotlin Deferred?

查看:36
本文介绍了如何将 Android 任务转换为 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完成

  • 暂停乐趣 signInAnonymous(): Unit

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

It returns a Deferred object, delivering the result asynchronously

  • fun signInAnonymous() : 推迟

推荐答案

kotlinx.coroutines.tasks 现在包括以下实用功能:

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

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

来自 文档:

等待任务完成而不阻塞线程.
此暂停功能是可取消的.
如果 Job当前协程在此挂起函数等待时被取消或完成,此函数停止等待完成阶段并立即以 CancellationException.

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> { ... }

来自 文档:

将此任务转换为 推迟.
如果任务被取消,那么由此产生的延迟也将被取消.

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()
}

或:

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

这篇关于如何将 Android 任务转换为 Kotlin Deferred?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆