firestore快照监听器生命周期和定价之间有什么关系?

2024-05-10

在我的活动中,我有一个字符串列表,这些字符串表示我想要附加快照侦听器的 Firestore 文档。我使用 Acivity - ModelView - 存储库结构。在活动的 onCreate 中,我向 ViewModelProvider 询问适当的 ViewModel。在 ViewModel 构造函数中,我调用以获取存储库(按照“带有视图的 Android room”教程”)。我的存储库负责附加 firestore 侦听器并将在线数据同步到我的本地数据库(android room) 。

我曾经与这些侦听器发生内存泄漏,即每次 Firestore 文档更改时,我的存储库都会尝试将其两个、三个、四个..副本下载到本地数据库中!我通过从活动的 onDestroy 一直调用存储库以删除侦听器来解决该问题。

我的问题是关于该解决方案的定价。我在 FireBase 网站上读到,快照侦听器每次启动时至少会算作一个“文档读取”,即使没有对文档进行任何更改。基本上,每次用户在我的应用程序中切换活动时,我都会删除并重新附加十多个侦听器(到完全相同的文档)。这是否意味着即使 30 分钟限制尚未到期,我也要为每一项活动更改支付阅读文档的费用?

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 客户端都必须连接到服务器以检查该侦听器观察到的文档是否已被修改。由于服务器必须为此读取文档,因此您确实需要为您观察到的每个文档所读取的文档付费。

如果你不想这样,你可以考虑告诉客户端从缓存中读取在源选项中指定 https://firebase.google.com/docs/firestore/query-data/get-data#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>() {
   ...

由于这是从本地缓存读取的,因此您无需为服务器上的读取付费,但这当然意味着您可能正在提供过时的数据。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

firestore快照监听器生命周期和定价之间有什么关系? 的相关文章

随机推荐