【问题标题】:Firebase async tasks to coroutinesFirebase 异步任务到协程
【发布时间】:2019-03-25 08:07:19
【问题描述】:

我已使用挂起例程构建器使 Firebase 任务从基于异步侦听器的代码转移到基于协程的代码。

这是我实现协程行为的挂起协程。

suspend fun <T> Task<T>.awaitTask(): T =
    suspendCoroutine { continuation ->
        addOnCompleteListener { task ->
            if (task.isSuccessful) {
                continuation.resume(task.result!!)//what to do if task.result is null
            } else {
                continuation.resumeWithException(task.exception!!)
            }
        }
    }

这就是我调用它的方式

firebase.createUserWithEmailAndPassword(userCredentials.email!!, userCredentials.password!!).awaitTask()

在我们执行一个有可能为空结果的任务之前,一切正常。像 。

firebase.currentUser?.updateProfile(profileUpdates)?.awaitTask()

这里更新成功后,task.result 为空。在这种情况下,应该将什么传递给 continuation.resume?。

【问题讨论】:

  • 可能是重复的,我想是helpful

标签: android kotlin firebase-authentication kotlin-coroutines


【解决方案1】:

您的返回类型应该可以为空,因为Task.getResult() 可以为空:

suspend fun <T> Task<T>.await() : T? = ...

如果您使用它来获得不可为空的结果,则在使用站点而不是在实现内部强制执行不可空性。

但是,既然它已经在 kotlinx-coroutines-play-services 中定义,为什么还要费心重新实现它?

【讨论】:

  • 调试时崩溃发生在这里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多