如何停止在 Firestore 中获取数据?

2024-01-26

我正在使用 Firestore 作为后端构建一个应用程序。我需要从数据库中获取每一个新的更改。

Code

EventListener<DocumentSnapshot> listener = new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException e) {
        if (snapshot != null && snapshot.exists()) {
            DataClass dataClass = snapshot.toObject(DataClass.class);
            processesData(dataClass); // process data from db.
        }
    }
};

ListenerRegistration listenerReg = dataDocumentReference.addSnapshotListener(listener);

当我关闭应用程序时,应用程序仍在获取数据。

我读到我可以关闭连接。我怎样才能做到这一点?


为了解决这个问题,您需要停止监听更改,这可以在您的onStop()方法通过调用remove()方法对你的ListenerRegistration像这样的对象:

@Override
protected void onStop() {
    super.onStop();

    if (listenerReg != null) {
        listenerReg.remove();
    }
}

请记住,当您使用添加快照监听器 https://firebase.google.com/docs/firestore/query-data/listen您附加一个侦听器,该侦听器会在数据库中发生的每个更改时被调用。因此,当您的应用程序关闭时也会发生这种情况,因此必须分离听众 https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener在活动被破坏之前。

如果在您的应用程序中您不需要实时获取数据,您可以使用get() https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document直接调用引用,只读取文档一次。由于它只读取一次,因此没有要删除的侦听器。这是本报记者addListenerForSingleValueEvent()用于 Firebase 实时数据库。

正如 @giudigior 在他的回答中所说,您还可以将您的活动作为第一个参数传递addSnapshotListener()方法,因此 Firestore 可以在 Activity 停止时自动清理侦听器。

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

如何停止在 Firestore 中获取数据? 的相关文章

随机推荐