Kotlin: Element Not Being Appended In The List
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):List
Solution 1:
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:
@WorkerThreadprivatefungetName(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).
Post a Comment for "Kotlin: Element Not Being Appended In The List"