I'm trying to access chatting room Using firestore and coroutines.

    fun getOwner() {
        runBlocking {
            var de = async(Dispatchers.IO) {
                firestore.collection("Chat").document("cF7DrENgQ4noWjr3SxKX").get()
            }
            var result = de.await().result
        }

但我会遇到这样的错误:

E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.example.map_fetchuser_trest, PID: 19329
    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 com.example.map_fetchuser_trest.model.Repository$getOwner$1.invokeSuspend(Repository.kt:53)

How can i get chat document? when i use origin api like below, I can access chat room document.

        firestore.collection("Chat").document(
            "cF7DrENgQ4noWjr3SxKX"
        ).get().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val chatDTO = task.result?.toObject(Appointment::class.java)
            }
        }

推荐答案

Task is the thing one awaits on, but you wrapped it in another layer of async. Remove the async:

fun getOwner() {
    runBlocking {
        var de =  firestore.collection("Chat").document("cF7DrENgQ4noWjr3SxKX").get()
        var result = de.await().result
    }
}

然而,如果使用runBlocking(),您就是搬起石头砸自己的脚,编写的阻塞代码只是正式使用异步API,但效果并不好.

To truly benefit from it, you must have a

suspend fun getOwner() = firestore
     .collection("Chat")
     .document("cF7DrENgQ4noWjr3SxKX")
     .get()
     .await()
     .result

and launch a coroutine at the place you call it from:

launch {
    val owner = getOwner()
    // update the GUI
}

This assumes you're calling launch from an object that is a CoroutineScope.

Kotlin相关问答推荐

文本正在被切断在200%的屏幕比例在Jetpack Compose

Kotlin中函数引用的否定

多模块Kotlin项目中的FreeFair

Kotlin接口方法默认值&;可传递依赖项

在 kotlin 原始字符串中转义三重引号

将 java Optional 转换为 Kotlin Arrow Option

如何使用成员引用在 Kotlin 中创建属性的分层路径

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

将子元素放在一个列表中

内联函数导致单元测试代码覆盖率报告出错

Kotlin - 当表达式返回函数类型

对列表中数字的子集求和

如何在 Kotlin 中为变量设置监听器

在 Koin 中提供一个 Instance 作为其接口

如果我可以将 Flow 和 StateFlow 与生命周期范围 \ viewLifecycleOwner.lifecycleScope 一起使用,那么在 ViewModel 中使用 LiveData 有什么意义

Kotlin 中的内联构造函数是什么?

Kotlin 扩展函数 - 覆盖现有方法

如何将map函数应用于Kotlin中的数组并更改其值?

ObserveForver是否了解生命周期?

可以在函数参数中使用解构吗?