Kotlin 如何从Firestore检索数据并将其存储在全局变量中
我似乎不知道如何将从Firestore检索到的数据存储在custom object类型的全局变量中。我可以从Kotlin 如何从Firestore检索数据并将其存储在全局变量中,kotlin,google-cloud-firestore,Kotlin,Google Cloud Firestore,我似乎不知道如何将从Firestore检索到的数据存储在custom object类型的全局变量中。我可以从.addOnSuccessListener中打印数据,但无法将数据分配给全局变量 我的代码如下: override fun getData(documentPath: String): ShopModel { var shopModel = ShopModel() firestore.firestoreSettings = FirebaseFirestor
.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
}
您必须在回调函数中指定全局变量的值(
addOnSuccessListener
),您不能在函数中返回该值,因为get()
是异步工作的,因此当您到达return
时,变量shopModel
中没有任何内容,直到执行回调,此时函数已返回一个空变量
这在前面已经解释过,get()是异步的,并且会立即返回。查询完成后,您提供的回调将在一段时间后调用。因此,您将无法从函数返回查询结果。相反,您应该考虑使用LiveData或协同程序来管理这种异步行为。谢谢,这帮了我的忙。