Johannes Pertl
Johannes Pertl

Reputation: 983

Is it possible to return Firestore data from a function?

In this code snippet, data gets retrieved from Firestore:

val docRef = db.collection("cities").document("BJ")
docRef.get().addOnSuccessListener { documentSnapshot ->
    val city = documentSnapshot.toObject<City>()
}

How could I turn this into a function, that returns a city object? Something like this:

fun getCity(): City?{
   val docRef = db.collection("cities").document("BJ")
   docRef.get().addOnSuccessListener { documentSnapshot ->
       val city = documentSnapshot.toObject<City>()
       return city
}

Can I somehow 'await' the result when I call the getCity() function?

Upvotes: 0

Views: 346

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317760

There's one important thing you'll need to know:

All Firestore APIs are asynchronous. They return immediately, and you must use the callback to get the results. There is no guarantee when the callback will be invoked, and it must be handled asynchronously. Your getCity() function will not be able to return an object immediately.

get() returns a Task object (provided by the Play services Task API) that represents the asynchronous query. If you want to await() the result of that, your easiest route is to use the kotlinx-coroutines-play-services library to convert that task into a suspend fun that can be awaited. If you do this, your getCity() should also be a suspend fun so that it can deliver the result asynchronously to its caller.

See also: How to use kotlin coroutines in firebase database

Upvotes: 2

Related Questions