在Kotlin上使用Cloud Firestore设置全局变量 [英] Setting global variable with Cloud Firestore on Kotlin

查看:91
本文介绍了在Kotlin上使用Cloud Firestore设置全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

:)我遇到了有关Cloud Firestore和Kotlin的问题.

again :) I got a question about Cloud Firestore and Kotlin.

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

I need to get data from firestore with some code like this:

    {
    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
}

变量'comments'填充在侦听器大括号内,但是当侦听器结束时,该值返回到0.

The variable 'comments' gets populated inside the listener curly brackets but when the listener ends, the value goes back to 0.

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

I've researched online and found examples in JAVA that works perfectly this way, for example: https://youtu.be/691K6NPp2Y8?t=246

我的目的是仅从Cloud Firestore一次获取数据,并将该值存储在全局变量(注释)中.

My purpose is to fetch data only ONCE from the Cloud Firestore and store that value in a global variable, comments.

请让我知道您是否对此有解决方案.

Please, let me know if you have a solution for this.

谢谢.

推荐答案

该值不会返回零".您应该了解数据库查询是异步的,并且addSnapshotListener在查询完成之前立即返回.最终值只有在一段时间后调用侦听器时才知道.

The value doesn't "go back to zero". You should understand that the database query is asynchronous, and addSnapshotListener returns immediately, before the query completes. The final value is only known when the listener is invoked some time later.

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

Also, you should know that if you just want to query a single time, you should use get() instead of addSnapshotListener(). It is also asynchronous and returns immediately, and the Task it returns will get invoked some time later. There are no synchronous options that block the caller until the query is complete - you will need to learn how to do your work asynchronously.

这篇关于在Kotlin上使用Cloud Firestore设置全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆