在LiveData返回功能中删除Firestore快照侦听器

时间:2018-07-03 15:34:08

标签: firebase kotlin google-cloud-firestore

我正在尝试优化应用程序的性能,但我注意到并未从存储库中删除Firestore侦听器。

我的存储库具有许多返回LiveData的函数,然后可以通过ViewModels的Transformations和视图进行观察。

一次性操作绝对可以正常工作(上载,删除等),但是活动完成后,永久侦听器不会收集垃圾。

现在,存储库中的函数如下所示:

// [...]
class Repository {   
  // [...]
  fun retrieveCode() {
  val observable = MutableLiveData<Code>()
  val reference = 
    FirebaseFirestore.getInstance().collection(/**/).document(/**/)

  reference
    .addSnapshotListener { snapshot, exception -> 
      if(exception != null) {
        observable.value = null
      }

      if(snapshot != null {
        observable.value = snapshot.//[convert to object]
      }
   }

   return observable
  }
}

我发现了一种解决方法,该方法是创建一个自定义LiveData对象,该对象将在监听器变为非活动状态时对其进行处理,如下所示:

class CodeLiveData(private val reference: DocumentReference): 
  LiveData<Code>(), EventListener<DocumentSnapshot>{
  private var registration: ListenerRegistration? = null

  override fun onEvent(snapshot: DocumentSnapshot?, 
    exception: FirebaseFirestoreException?) {
    if(exception != null) {
      this.value = null
    }

    if(snapshot != null) {
      this.value = snapshot.//[convert to object]
    }
  }

  override fun onActive() {
    super.onActive()
    registration = reference.addSnapshotListener(this)
  }

  override fun onInactive() {
    super.onInactive()
    registration?.remove()
  }
}

有没有一种方法可以解决此问题,而无需创建自定义类,而是通过改进类似于第一个示例的功能?

谢谢

Emilio

1 个答案:

答案 0 :(得分:3)

有两种方法可以实现此目的。第一个是停止监听更改,这可以通过在onStop()对象上调用remove()函数来在ListenerRegistration函数中完成,如下所示:

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

方法是让您将活动作为addSnapshotListener()函数中的第一个参数传递,因此Firestore可以在活动停止时自动清除侦听器。

var registration = dataDocumentReference
        .addSnapshotListener(yourActivity, listener)
相关问题