首頁 > Java > java教程 > 主體

在FirebaseUI-Android RecyclerView中使用快照監聽器時如何避免資源外洩?

Barbara Streisand
發布: 2024-10-26 21:16:02
原創
330 人瀏覽過

 How to Avoid Resource Leaks When Using Snapshot Listeners in FirebaseUI-Android RecyclerView?

在FirebaseUI-Android RecyclerView 中新增和刪除快照偵聽器

FirebaseUI-Android 提供了一種使用即時資料填充RecyclerView 的RecyclerView 的便捷方法消防店。但是,了解如何正確新增和刪除快照監聽器以避免資源洩漏非常重要。

新增快照監聽器

使用 FirebaseRecyclerAdapter 時,會新增一個監聽器RecyclerView 中的每個項目。在 populateViewHolder 方法中,您可以使用 getRef(i) 方法來擷取目前專案的 DocumentReference。

要監聽引用的更改,您可以使用 addSnapshotListener(EventListener) 方法。此方法採用 EventListener 作為參數,只要引用的快照發生更改,就會呼叫此方法。

刪除快照偵聽器

刪除偵聽器至關重要當不再需要它時。如果不這樣做將導致內存洩漏。您可以使用ListenerRegistration物件上的remove()方法刪除監聽器。

populateViewHolder方法中的實作

以下是如何新增和刪除快照的範例FirebaseRecyclerAdapter 的populateViewHolder 方法中的偵聽器:

在此範例中,listenerRegistration 變數初始化為null。然後,在 if 語句中,如果尚未新增監聽器,則將其新增。
@Override
protected void populateViewHolder(final ConvViewHolder convViewHolder, final Conv conv, int i) {
    final String list_user_id = getRef(i).getKey();
    final DocumentReference docRef = db.collection("cities").document(list_user_id);
    ListenerRegistration listenerRegistration = null;
    if (listenerRegistration == null) {
        listenerRegistration = docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot snapshot,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.w(TAG, "Listen failed.", e);
                    return;
                }
                if (snapshot != null && snapshot.exists()) {
                    Log.d(TAG, "Current data: " + snapshot.getData());
                } else {
                    Log.d(TAG, "Current data: null");
                }
            }
        });
    }
}
登入後複製

在Activity 生命週期方法中刪除監聽器

要在以下情況下刪除監聽器: Activity 不再可見,您可以重寫Activity 中的onStop( ) 方法,並呼叫ListenerRegistration 上的remove() 方法。

透過執行以下步驟,您可以確保快照偵聽器正確新增和刪除,防止資源洩漏並提高應用程式的效能。
@Override
protected void onStop() {
    super.onStop();
    if (listenerRegistration != null) {
        listenerRegistration.remove();
    }
}
登入後複製

以上是在FirebaseUI-Android RecyclerView中使用快照監聽器時如何避免資源外洩?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!