首页 > 解决方案 > 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)

标签: androidfirebasekotlinasync-awaitkotlin-coroutines

解决方案


继续使用 Tasks API:

try {
    val result = Tasks.await(userRef.get(), 2, TimeUnit.SECONDS)
    Result.build { result }
}
catch (e : Exception) {
    Result.Error(e)
}

推荐阅读