【问题标题】:Is it possible to return Firestore data from a function?是否可以从函数返回 Firestore 数据?
【发布时间】:2020-10-03 07:42:40
【问题描述】:

this code snippet 中,从 Firestore 中检索数据:

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

我怎样才能把它变成一个函数,返回一个城市对象?像这样的:

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

当我调用 getCity() 函数时,我能以某种方式“等待”结果吗?

【问题讨论】:

    标签: firebase kotlin google-cloud-firestore


    【解决方案1】:

    您需要知道一件重要的事情:

    所有 Firestore API 都是异步的。它们立即返回,您必须使用回调来获取结果。无法保证何时调用回调,必须异步处理。 您的getCity() 函数将无法立即返回对象。

    get()返回一个代表异步查询的Task对象(由Play services Task API提供)。如果你想await() 得到那个结果,你最简单的方法是使用kotlinx-coroutines-play-services 库将该任务转换为可以等待的suspend fun。如果您这样做,您的getCity() 也应该是suspend fun,以便它可以将结果异步传递给它的调用者。

    另见:How to use kotlin coroutines in firebase database

    【讨论】:

      猜你喜欢
      • 2018-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      相关资源
      最近更新 更多