Chris
Chris

Reputation: 4728

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');

Upvotes: 4

Views: 5539

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

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.

Upvotes: 10

Related Questions