Kotlin 协程和 Android - 获取 Firestore 查询任务结果的结果

241*_*116 1 android kotlin google-cloud-firestore

我正在编写一个函数,该函数对 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)
            }
    }
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试做的 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dou*_*son 7

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

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

因此,将库添加到您的项目中,如下所示:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.2.1'
Run Code Online (Sandbox Code Playgroud)

然后创建一个挂起函数,如下所示:

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

然后你可以从另一个挂起函数中调用它,如下所示:

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

您需要了解如何在 Android 环境中创建协程上下文,以便您可以开始使用挂起函数。对此进行全面讨论超出了本问题的范围。有很多 Android 文档和教程可以帮助您解决此问题。