【问题标题】:Kotlin: Element not being appended in the list [duplicate]Kotlin:元素未附加到列表中[重复]
【发布时间】:2020-12-11 11:59:11
【问题描述】:

我正在使用 kotlin 制作一个 android 应用程序,但我目前面临一个奇怪的问题。问题所在的函数是这样的:

private fun getName(uids:List<String>):List<String> {
        val nameList = mutableListOf<String>()
        for (uid in uids) {
            Firebase.firestore.collection("users").whereEqualTo("id", uid).get().addOnSuccessListener { documents ->
                    val name = documents.documents[0]["name"] as String
                    println("The name is $name")
                    nameList.add(name)
                    println("The namelist is $nameList")
                }
            println("The data above is $nameList")
        }
        println("The datahere is $nameList")
        return nameList.toList()
    }

这里我有一些用户 ID,基于这些 ID,我从 Firebase Cloud Firestore 数据库中获取名称,数据被成功获取,当我第一次在获取块内打印 namelist 时,正在添加一个元素。但是,当我在提取块之外打印 nameList 时,我看到该元素没有添加。我附上了一张图片。

如您所见,正在添加元素。但在那之后,元素消失,列表变为空。

我真的很困惑为什么会这样。

【问题讨论】:

  • addOnSuccessListener 函数接受一个在下载数据时调用的回调。这发生在当前函数使用 print 语句执行之后。

标签: android firebase kotlin asynchronous google-cloud-firestore


【解决方案1】:

原因是您希望异步作业充当同步作业。正如我们所知,从firestore 检索数据是一个异步过程(请注意addOnSuccessListener)。因此,当函数返回nameList(以及最后一个println)时,它是空的,因为尚未检索到来自firestore 的任何结果!


由于DocumentReference.get() 返回一个Task 对象,因此可以等待它。所以,你的函数可能是这样的:

@WorkerThread
private fun getName(uids: List<String>) {
    val nameList = mutableListOf<String>()
    for (uid in uids) {
        val task = Firebase.firestore.collection("users").whereEqualTo("id", uid).get()
        val documentSnapshot = Tasks.await(task)
        val name = documentSnapshot.documents[0]["name"] as String
        nameList.add(name)
    }
    nameList.toList()
}

请注意,在这种情况下,您应该在工作线程(而不是主线程)中调用此函数。

【讨论】:

  • 你能告诉我如何使这个异步
  • 实际上,我收到一条错误消息“不得在主应用程序线程上调用”。我使用了完全相同的代码。
  • 我已经在答案的最后一行提到了。最简单的方法是运行一个线程并在其中调用这个函数。例如:Thread { val result = getName(...) /* do whatever with the result */ }.start()
猜你喜欢
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 2018-05-19
  • 2020-03-30
相关资源
最近更新 更多