How to return a list from Firestore database as a result of a function in Kotlin?

前端 未结 3 1550
死守一世寂寞
死守一世寂寞 2020-11-22 01:56

I\'m building an app for a friend and I use Firestore. What I want is to display a list of favorite places but for some reason, the list is always empty.

I

3条回答
  •  既然无缘
    2020-11-22 02:16

    Nowadays, Kotlin provides a simpler way to achieve the same result as in the case of using a callback. This answer is going to explain how to use Kotlin's coroutines. In order to make it work, we need to add the following dependency in our build.gradle file:

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.2.1"
    

    This library that we use is called Module kotlinx-coroutines-play-services and is used for the exact same purpose. As we already know, there is no way we can return a list of objects as a result of a method because get() returns immediately but the callback from the Task it returns will be called sometime later. That's the reason we should wait until the data is available.

    On the Task object that is returned when calling get(), we can attach a listener so we can get the result of our query. What we need to do now is to convert this into something that is working with Kotlin's coroutines. For that, we need to create a suspend function that looks like this:

    private suspend fun getListOfPlaces(): List {
        val snapshot = placesRef.get().await()
        return snapshot.documents
    }
    

    As you can see, we have now an extension function called await() that will interrupt the coroutine until the data from the database is available and then return it. Now we can simply call it from another suspend method like in the following lines of code:

    private suspend fun getDataFromFirestore() {
        try {
            val listOfPlaces = getListOfPlaces()
        }
        catch (e: Exception) {
            Log.d(TAG, e.getMessage()) //Don't ignore errors!
        }
    }
    

提交回复
热议问题