gpt4 book ai didi

firebase - Firestore.getInstance() : how to use?

转载 作者:行者123 更新时间:2023-12-05 00:11:08 26 4
gpt4 key购买 nike

Firebase Firestore 提供 getInstance()方法,它打开一个套接字(在应用程序执行的任何时候只有一个)并实例化 Firestore 客户端。

我想查询和存储数据,使用或不使用监听器(以获取实时更新等)。如果我调用 getInstance只要我需要查询或存储,或者当我的应用程序启动时将此实例存储在静态类中,然后在需要查询或存储时立即使用此静态类属性:这两种情况在技术上是相同的。因为谷歌使用单例模式( getInstance() )。

但我错过了什么吗?将此实例存储为静态类属性并在需要时使用它实际上是否安全?调用getInstance真的安全吗?每当我需要它? 更明确地说:在两次调用 getInstance() 之间(或在对静态类属性的 2 次访问之间),即:在 2 个执行时间点之间,是否存在丢失网络连接、套接字连接、实时监听器(快照)连接等的风险?

如果是:如何处理这些问题?

最佳答案

I would want to query and store data, using or not listeners (to get realtime updates, etc.)



如果不使用监听器,就无法获取数据甚至获取实时更新。 Cloud Firestore 中的一切都与听众有关。

if I store this instance in a static class when my app starts and then use this static class attribute as soon as I need to query or store



不要将 Android 上下文类放在静态字段中。对具有指向 Context 的字段上下文的 FirebaseFirestore 的静态引用将导致内存泄漏。

静态字段会泄漏上下文。非静态内部类具有对其外部类的隐式引用。如果该外部类例如是 Fragment 或 Activity,则此引用意味着长时间运行的处理程序/加载程序/任务将持有对该 Activity 的引用,从而防止其被垃圾收集。

因此,不要将其存储为静态变量调用 getInstance()任何时候都需要。或者更方便的解决方案是使用依赖注入(inject)。 Dagger可以帮你解决。

And is it really safe to call getInstance whenever I need it?



是的。

between 2 accesses to the static class attribute), i.e.: between 2 points of execution time, is there any risk to loose network connection, socket connection, realtime listeners (snapshots) connection, etc. ?



请看上面的解释。

关于firebase - Firestore.getInstance() : how to use?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54717505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com