Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubscribing from Firebase Realtime Database

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');
like image 995
Chris Avatar asked Jan 28 '23 21:01

Chris


1 Answers

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.

like image 183
Doug Stevenson Avatar answered Jan 30 '23 12:01

Doug Stevenson