【问题标题】:Kotlin coroutines and Android - get the result of a Firestore query Task resultKotlin 协程和 Android - 获取 Firestore 查询任务结果的结果
【发布时间】:2019-11-30 17:44:23
【问题描述】:

我正在编写一个对 firestore 文档进行查询并在列表中返回它们的函数。如果没有文档,则返回 null(或空列表)。我对Kotlin不是很熟悉,我只知道Flutter

Kotlin 代码(我尝试过的)但它说我无法在侦听器内部返回:

fun getPlaces(type: String): List<DocumentSnapshot>? {
        db.collection("users")
            .whereEqualTo("type", type)
            .get()
            .addOnSuccessListener { documents ->
                if (documents.isEmpty) {
                    return null
                } else {
                    return documents
                }
            }
            .addOnFailureListener { exception ->
                Log.w(TAG, "Error getting documents: ", exception)
            }
    }

这是我正在尝试做的 Flutter 等价物:

List<DocumentSnapshot> getDocs(String type) async {
    QuerySnapshot snaps = await db.collection('users').where('type', isEqualTo: type).getDocuments();

    if (snaps.documents.isEmpty) {
        return null;
    } else {
        return snaps.documents;
    }
}

语法可能有点不对,但类似

【问题讨论】:

  • 如果你想在 Kotlin 中以“正确的方式”做到这一点,以最接近你展示的飞镖的方式,你将不得不学习带有“暂停”的 Kotlin 协程函数以处理来自查询的异步响应。如果您是 Kotlin 的新手,这将需要深入了解该语言的细节以及添加到其中的 Android 平台框架。
  • 那么在侦听器外部定义var docs: List&lt;DocumentSnapshot&gt;? = null 并将docs = documents.documents 放在侦听器内部不起作用?我只需要在完成查询后将文档存储在列表中

标签: android kotlin google-cloud-firestore


【解决方案1】:

这个答案将假设您已经了解 Kotlin 协程在 Android 环境中的工作原理。 Android 平台团队强烈建议这种做法。

如您所见,get() 立即返回一个 Task 对象,您可以在其中附加侦听器以获取查询结果。您需要做的是将其转换为可与 Kotlin 协程一起使用的东西。有一个名为kotlinx-coroutines-play-services 的库。这将为您提供一个名为 await() 的扩展函数,它将暂停协程直到结果可用,然后返回它。

所以,像这样将库添加到您的项目中:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.2.1'

然后像这样创建一个挂起函数:

private suspend fun getPlaces(type: String): List<DocumentSnapshot> {
    val querySnapshot = db.collection("users")
        .whereEqualTo("type", type)
        .get()
        .await()
    return querySnapshot.documents
}

然后你会像这样从另一个挂起函数调用它:

private suspend fun foo() {
    try {
        val places = getPlaces("...")
    }
    catch (exception: Exception) {
        Log.w(TAG, "Error getting documents: ", exception)
    }
}

您可以学习如何在 Android 环境中创建协程上下文,以便开始使用挂起函数。关于这个问题的完整讨论超出了这个问题的范围。有很多 Android 文档和教程可以帮助解决这个问题。

【讨论】:

  • 感谢您的回复,我最终使用了类似于我最初使用的东西(我只需要根据从 firestore 返回的文档创建一个下拉(微调器)。这是一个快速的学校项目) .但我一定会在未来学习你的方法来制作更严肃的应用程序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 2021-09-11
  • 2021-04-19
  • 2021-05-13
  • 2020-06-18
  • 2022-01-14
相关资源
最近更新 更多