【问题标题】:Setting global variable with Cloud Firestore on Kotlin在 Kotlin 上使用 Cloud Firestore 设置全局变量
【发布时间】:2020-04-09 05:35:20
【问题描述】:

再次 :) 我有一个关于 Cloud Firestore 和 Kotlin 的问题。

我需要使用如下代码从 firestore 获取数据:

    {
    val comments = mutableListOf<Comment>()

    val firestore = FirebaseFirestore.getInstance()
    firestore.collection(collection).document(documentID).collection("comments")
        .addSnapshotListener { querySnapshot, firebaseFirestoreException ->
            comments = querySnapshot?.toObjects(Comment::class.java)!!

            // do something with 'comments'. Works: comments is populated

        }

    // do something with variable 'comments'. Doesn't work: comments is now empty
}

变量 'cmets' 填充在侦听器大括号内,但当侦听器结束时,该值又回到 0。

我在网上进行了研究,发现 JAVA 中的示例可以完美地以这种方式运行,例如: https://youtu.be/691K6NPp2Y8?t=246

我的目的是仅从 Cloud Firestore 中获取一次数据,并将该值存储在全局变量 cmets 中。

如果您对此有解决方案,请告诉我。

谢谢。

【问题讨论】:

  • 检查 thisthis
  • 谢谢你,Alex,我让它与接口示例一起工作。我现在在“onCreate”中从 firebase 获取数据,稍后单击按钮时会使用它。

标签: android kotlin google-cloud-firestore


【解决方案1】:

该值不会“归零”。您应该了解数据库查询是异步的,addSnapshotListener 在查询完成之前立即返回。最终值只有在稍后调用侦听器时才知道。

另外,你应该知道,如果你只想查询一次,你应该使用get()而不是addSnapshotListener()。它也是异步的并立即返回,它返回的任务将在一段时间后被调用。在查询完成之前,没有同步选项会阻止调用者 - 您需要学习如何异步完成工作。

【讨论】:

  • 道格,感谢您的超快答复。我正在研究协程,我想我可以让它工作。再次感谢 ! :)
猜你喜欢
  • 1970-01-01
  • 2021-05-18
  • 2019-10-10
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多