Home > front end >  Returning a value which is inside of add on Success Listener in kotlin
Returning a value which is inside of add on Success Listener in kotlin

Time:03-24

I am facing a problem to get a return type in a function in kotlin

The function is

 override suspend fun uploaded_docs_retrival() : ArrayList<String> {

    Firebase.firestore.collection("profiles").whereEqualTo("uid", "$uid").get()
        .addOnSuccessListener { result ->
        for (document in result) {
            val myObject = document.toObject(docretreving::class.java)
            val x = myObject.Docs
        }

    }
    return x
}

Here I am retrieving the information from Fire store Mapping it to a object

However in above Function I am unable to return x as it says x is unresolved

My data class is as Follows:

data class docretreving(
val Docs : ArrayList<String> = arrayListOf<String>()

)

How do I write the code in such a way that I can return value x which is a Array list from my function uploaded_docs_retrival()

CodePudding user response:

You are getting 'x is unresolved' because the scope of 'val x' is within the for loop.

You won't be able to access it outside the loop and listener.

The best way to get list of strings, is to pass a listener as parameter to the method. You can also pass the 'SuccessListener' to get the values.

override suspend fun uploaded_docs_retrival(listener : SuccessListener) = Firebase.firestore.collection("profiles").whereEqualTo("uid","$uid").get() .addOnSuccessListener(listener)

CodePudding user response:

Call await() instead of adding a success listener. Wrap it in try/catch because it throws an exception on failure.

I'm not sure exactly why you're returning a single item when Firestore can return multiple. I'm just taking the first item in the results below:

override suspend fun uploaded_docs_retrival() : ArrayList<String> {
    return try {
        val result = Firebase.firestore.collection("profiles").whereEqualTo("uid", "$uid").get()
            .await()
        require(result.isNotEmpty()) { "No values returned." }
        result.first().toObject(docretreving::class.java).Docs
    } catch(e: Exception) {
        Log.e(TAG, "Failed to upload: ${e.message.orEmpty()}")
        ArrayList() // or you can rethrow or return null if you want
    }
}

If you don't have access to the await() extension function, add this dependency in build.gradle:

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.0"
  • Related