【问题标题】:How to retrieve data from Firestore and store it in global variable [duplicate]如何从 Firestore 中检索数据并将其存储在全局变量中 [重复]
【发布时间】: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


【解决方案1】:

您必须在回调 (addOnSuccessListener) 内分配全局变量的值,您不能在函数内返回该值,因为 get() 异步工作,因此当您到达 return 时,变量 shopModel在执行回调之前,其中没有任何内容,到那时该函数已经返回并带有一个空变量。

这在herehere之前已经解释过了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2018-11-13
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多