android - Kotlin协程java.lang.IllegalStateException:任务尚未完成,即使任务返回值
问题描述
我正在尝试使用 await() 从 firebase 检索数据,当我尝试在没有结果包装器的情况下执行此操作时,代码可以工作,但同样的事情会崩溃:“java.lang.IllegalStateException:任务尚未完成”
下一个代码崩溃
suspend fun isUserRegisteredOnServer(): Result<Exception, Boolean> =
try {
val result = userRef.get().await().exists()
Result.build { result }
}
catch (e : Exception) {
Result.Error(e)
}
以下不
suspend fun tempIsRegistered() : Boolean
{
return userRef.get().await().exists()
}
结果类:
sealed class Result <out E,out V > {
data class Value<out V>(val value : V) : Result<Nothing, V>()
data class Error<out E>(val error : E) : Result<E, Nothing>()
companion object Factory
{
inline fun <V> build(function : () -> V): Result<Exception, V> =
try {
Value(function.invoke())
}catch (e: Exception) {
Error(e)
}
}
}
还值得注意的是,我正在调用这些函数
CoroutineScope(IO).launch {}
堆栈跟踪:
2019-09-05 18:50:54.121 23507-23561/E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: , PID: 23507
java.lang.IllegalStateException: Task is not yet complete
at com.google.android.gms.common.internal.Preconditions.checkState(Unknown Source:29)
at com.google.android.gms.tasks.zzu.zzb(Unknown Source:121)
at com.google.android.gms.tasks.zzu.getResult(Unknown Source:12)
at firebase.database.FirestoreDatabaseRepository.fetchUserLists(FirestoreDatabaseRepository.kt:79)
at com.mainfragment.MainFragmentViewModel$handleEvent$1.invokeSuspend(MainFragmentViewModel.kt:74)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
解决方案
继续使用 Tasks API:
try {
val result = Tasks.await(userRef.get(), 2, TimeUnit.SECONDS)
Result.build { result }
}
catch (e : Exception) {
Result.Error(e)
}
推荐阅读
- xpath - 使用 ImportXML 将来自 goodreads.com 的书名导入 Google 表格有时会出现“导入内部错误”
- database - 在 char(2) 列上使用 trim 并且数据库字段只有空格时,Oracle Select 查询不返回任何结果
- c - 试图删除 malloc 的使用 - 这里有替代方案吗?
- kotlin - 线程何时会挂起挂起功能?
- javascript - 如何将两张图片合成一张图片并在 Javascript 中更改颜色?
- spring-boot - 在 Spring Boot 中根据登录用户更改应用程序的 URL
- swift - Swift 可重用模型类/结构
- php - 当我已经在我的 Web.php 中定义了资源控制器时,没有定义路由 [controller.create]
- python - S3 Kedro 数据集是线程安全的吗?
- php - 如何在php中使两个数组彼此等效?