Firebase 9.0.0上取消订阅的正确方法



在以前的版本中,我会这样做:

// 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)

Firebase 9.0.0之后,我看到onValue()函数返回一个Unsubscribe回调:

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

因此,我当前的方法:

// Declaring db reference
let featuresRef = ref(db, 'features')
// Creating the listener
let unsubscribe = onValue(featuresRef, snapshot => { 

if(snapshot.val()){    
// Reading data
}

})
// Unsubscribing       
unsubscribe()

我在函数定义中看到off()函数仍然存在,并且根据文档:

回调被删除通过调用off()方法在你的Firebase数据库引用。

是否需要使用返回的Unsubscribe回调函数或off()函数删除侦听器?

firebase here

返回的函数和off都可以用来删除侦听器。没有功能上的区别,甚至在新SDK中,它们在很大程度上是相同的。

从Firebase实时数据库sdk的第一个版本开始,off()样式的退订功能就已经可用了。随着时间的推移,较新的Firebase产品开始返回退订功能,许多开发人员似乎更喜欢这个功能,所以我们在v9 SDK中添加了这种退订功能。但off也仍然可用,并且功能相同。

最新更新