【发布时间】:2020-08-25 21:04:02
【问题描述】:
我似乎不知道如何将我从 Firestore 检索到的数据存储在自定义对象类型的全局变量中。我可以从.addOnSuccessListener 中打印出数据,但我无法将数据分配给全局变量。
我的代码如下:
override fun getData(documentPath: String): ShopModel {
var shopModel = ShopModel()
firestore.firestoreSettings = FirebaseFirestoreSettings.Builder().build()
val document = firestore.collection("shops").document(documentPath)
document.get().addOnSuccessListener {
shopModel = it.toObject(ShopModel::class.java)!!
info(shopModel) //this prints the model out and it works
}
return shopModel //this returns an object with empty fields
}
【问题讨论】:
-
get() 是异步的并立即返回。您提供的回调会在查询完成后的一段时间后调用。因此,您将无法从函数返回查询结果。相反,您应该考虑使用 LiveData 或协程来管理这种异步行为。
标签: kotlin google-cloud-firestore