Home > Blockchain >  Correct way to unsubscribe on Firebase 9.0.0
Correct way to unsubscribe on Firebase 9.0.0

Time:09-24

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?

CodePudding user response:

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.

  • Related