Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to unsubscribe on Firebase 9.0.0

On previous versions, I would do:

// Declaring db reference
let ref = firebase.database().ref('features')

// Creating the listener
let listener = ref.on('value', snapshot => { 
            
    if(snapshot.val()){
        // Reading data
    }

}

// Unsubscribing
ref.off('value', listener)

After Firebase 9.0.0, I've seen that the onValue() function returns an Unsubscribe callback:

/** A callback that can invoked to remove a listener. */
export declare type Unsubscribe = () => void;

Thus, my current approach:

// Declaring db reference
let featuresRef = ref(db, 'features')

// Creating the listener
let unsubscribe = onValue(featuresRef, snapshot => { 
            
    if(snapshot.val()){    
        // Reading data
    }
            
})

// Unsubscribing       
unsubscribe()

I see on the functions definition that the off() function still exists, and per the documentation:

Callbacks are removed by calling the off() method on your Firebase database reference.

Do I need to use the returned Unsubscribe callback function or the off() function to remove the listener?

like image 720
Erik Martín Jordán Avatar asked Oct 18 '25 07:10

Erik Martín Jordán


1 Answers

firebaser here

Both the returned function and off can be used to remove the listener. There is no functional difference, and even under the hood they are largely the same in the new SDK.

The off() style of unsubscribing has been available in the Firebase Realtime Database SDKs since their very first version. Somewhere along the line, newer Firebase products started returning an unsubscribe function and many developers seem to prefer that, so we added that style of unsubscribe in the v9 SDK. But off is also still available, and is functionally identical.

like image 155
Frank van Puffelen Avatar answered Oct 21 '25 03:10

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!