4

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?

Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36
  • 1
    Both the returned function and `off` can be used to remove the listener. Are you having problems with either of them? – Frank van Puffelen Sep 23 '21 at 15:23
  • No, just curious if there were any differences between both approaches. I will let the Unsubscribe callback because it seems more readable. – Erik Martín Jordán Sep 23 '21 at 15:29
  • 1
    That's precisely why it was introduced in this major change. We all like the new pattern better, but didn't want to completely remove the old metaphor. I'll write up a quick answer to give some closure. – Frank van Puffelen Sep 23 '21 at 16:41

1 Answers1

5

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807