元素未添加到列表中

元素未添加到列表中

本文介绍了Kotlin:元素未添加到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making an android app with kotlin, but I am currently facing a strange issue. The function where the issue is this:

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 时,我看到该元素未添加.我已附上图片.

Here I have a few ids of the user and based on these ids I am fetching the name from the Firebase Cloud Firestore database, the data is successfully being fetched and when I print the namelist first time inside the fetching block, an element is being added. However, when I print the nameList outside the fetching block, I see that the element does not add. I have attached an image.

您可以看到正在添加元素.但是之后,该元素消失了,列表变为空.

As you can see the element is being added. But after that, the element disappears and the list becomes empty.

我真的很困惑为什么发生这种情况.

I am really confused as to why this is occurring.

推荐答案

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

The cause is that you want an async job to act as a sync one. As we know such retrieving data from firestore is an async procedure (get attention to addOnSuccessListener). So when the function returns nameList (as well as the last println), it is empty because any of the results from firestore has not retrieved yet!

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

As DocumentReference.get() returns a Task object it's possible to wait on it. So, your function could be something like this:

@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()
}

请注意,在这种情况下,您应该在辅助线程(而非主线程)中调用此函数.

Notice that in this case, you should call this function in a worker thread (not main thread).

这篇关于Kotlin:元素未添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:03