Unsubscribing from Firebase Realtime Database

血红的双手。 提交于 2020-05-29 10:21:59

问题


I have a chat system within my Ionic app that is displayed within a modal window. Within the modal window I have the code below. It seems that after using the app for a while it becomes a bit sluggish.

I suspect that it's because I should be unsubscribing from Firebase when I close the modal window. In other words, it seems like a new subscription is being made each time I click the button to open the modal. Is this the case? If so, what should I do? I don't see an unsubscribe option in the docs?

ionViewDidLoad() {
    firebase.database().ref('chatrooms/'+this.roomkey+'/chats').limitToLast(30).on('value', resp => {

        this.chats = [];
        this.chats = snapshotToArray(resp);
        this.content.scrollTo(0, 999999, 200);

    });
}

I have tried the following to call off but unsure if it is the correct approach? I have put this within ionViewDidLeave()

firebase.database().ref('chatrooms/'+this.roomkey+'/chats').limitToLast(30).off('value');

回答1:


You should always remove any listeners on a database reference when that listener is no longer needed. Otherwise, that listener will continue to receive snapshots when data changes.

To remove a listener, use the off() method on the same reference that you used to call on(). Pass it the callback function that you passed on on(). Please also read the documentation for detatching listeners.



来源:https://stackoverflow.com/questions/51011828/unsubscribing-from-firebase-realtime-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!