Setting global variable with Cloud Firestore on Kotlin

别说谁变了你拦得住时间么 提交于 2021-02-11 17:44:47

问题


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

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
}

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

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

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.

Thank you.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/61114584/setting-global-variable-with-cloud-firestore-on-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!