在我的 Activity 中,我有一个字符串列表,这些字符串代表我想要附加快照监听器的 firestore 文档。我使用 Activity - 模型 View - 存储库结构。在 Activity 的 onCreate 中,我向 ViewModelProvider 询问适当的 ViewModel。在 ViewModel 构造函数中,我调用以获取存储库(根据“带 View 的 Android 房间”教程“)。我的存储库负责附加 firestore 监听器并将在线数据同步到我的本地数据库(android 房间) .
我曾经与这些监听器发生内存泄漏,即每次 Firestore 文档更改时,我的存储库都试图将其下载两、三、四..副本到本地数据库中!我解决了这个问题,方法是从我的 Activity 的 onDestroy 一直调用到存储库以删除监听器。
我的问题 是关于这个解决方案的定价。我在 FireBase 网站上读到,快照监听器在每次启动时至少算作一次“文档读取”,即使没有对文档进行任何更改。基本上,每次用户在我的应用程序中切换 Activity 时,我都会删除并重新附加十几个监听器(到完全相同的文档)。这是否意味着即使 30 分钟的限制尚未结束,我也要为每一项 Activity 更改支付一份文件阅读费用?
Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMessageViewModel = new ViewModelProvider(this).get(MessageViewModel.class);
// ....
}
@Override
public void onDestroy(){
mMessageViewModel.removeListeners();
super.onDestroy();
}
查看型号
public MessageViewModel (Application application) {
super(application);
mRepository = new MessageRepository(application);
}
public void removeListeners(){
mRepository.removeListeners();
}
// ...
存储库
private List<ListenerRegistration> my_listeners;
private List<String> my_list;
MessageRepository(Application application) {
MessageRoomDatabase db = MessageRoomDatabase.getDatabase(application);
mMessageDao = db.messageDao();
firedb = FirebaseFirestore.getInstance();
attachListeners();
}
public void attachListeners(){
for(String item : my_list){
colRef = firedb.collection("items").document(item).collection("sub-items");
ListenerRegistration my_listener_registration = colRef
.addSnapshotListener(myListener);
my_listeners.add(my_listener_registration);
}
}
public void removeListeners(){
for(ListenerRegistration my_listener : my_listeners){
my_listener.remove();
}
}
// ...
最佳答案
每次附加监听器时,Firestore 客户端都必须连接到服务器以检查该监听器观察到的文档是否已被修改。由于服务器必须为此读取文档,因此您确实需要为您观察到的每个文档读取的文档付费。
如果不想这样,可以考虑通过specifying that in the source options告诉客户端从缓存中读取.
DocumentReference docRef = db.collection("cities").document("SF"); // Source can be CACHE, SERVER, or DEFAULT. Source source = Source.CACHE; // Get the document, forcing the SDK to use the offline cache docRef.get(source).addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { ...
由于这是从本地缓存读取的,因此您不会为服务器上的读取付费,但这当然意味着您可能正在提供陈旧的数据。
关于java - firestore 快照监听器的生命周期和定价之间有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419258/