This is not a duplicate and the suggested link is for JAVA but I am looking for Kotlin
I wanted to write a method that will return the value of a particular field of a document in Firestore. I know how to get the value but I am not able to return the value.
This is what I have.
fun getCurrentUserType(): String {
var userType = ""
mFireStore.collection("users")
.document(getCurrentUserID())
.get()
.addOnSuccessListener { document ->
val usrType: String? = document.getString("user_type")
if (usrType != null) {
userType = usrType
}
}
return userType
}
As you know, this return statement executes before getting the data from the Firestore, so it's of no use.
As I read on Stackoverflow, the return method has to be in an addOnCompleteListener. I cannot call addOnCompleteListener in the above code that I have and I tried doing it as follows but that doesn't work. Can you help, please?
I get the correct value in the Logcat though using the following code.
Following is how tried.
fun getCurrentUserType(): String {
mFireStore.collection("users").get().addOnCompleteListener { task ->
if (task.isSuccessful) {
val list = ArrayList<String>()
for (document in task.result) {
val userType = document.data["user_type"].toString()
list.add(userType)
}
Log.d("UserType is ", list[0])
val userTye = list[0]
return@addOnCompleteListener userTye
}
}
}