Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Element not being appended in the list [duplicate]

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

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.

like image 997
programmer pro Avatar asked Dec 18 '25 08:12

programmer pro


1 Answers

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!


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).

like image 86
aminography Avatar answered Dec 20 '25 21:12

aminography



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!