我是否应该删除ValueEventListener? [英] Should I actually remove the ValueEventListener?
问题描述
DatabaseReference Ref = FirebaseDatabase.getInstance().getReference(Constants.Client + "/" + path);
Ref.keepSynced(true);
Ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我了解到ValueEventListener
运行在新线程中,实际上我应该在任何时间删除此线程以进行适当的线程管理吗? (例如,没有太多并行运行的线程).如果是,该怎么办?
I understand that ValueEventListener
runs in a new thread, should I actually remove this at any point of time for proper thread management? (example for not too many threads running in parallel). If yes, how to do it?
推荐答案
在谈论监听器时,是的,您需要根据活动的生命周期将其删除,为此,您需要使用以下代码行:
When talking about listeners, yes, you need to remove them accordingly to the life-cycle of your activity and for this you need to use the following line of code:
databaseReference.removeEventListener(valueEventListener);
请记住,如果不这样做,最终将浪费电池和带宽.所以:
Remember if you don't do this, you'll end up wasting your battery and bandwidth. So:
- 如果已在
onStart
中添加了侦听器,则必须在onStop
中将其删除. - 如果已在
onResume
中添加了侦听器,则必须在onPause
中将其删除. - 如果已在
onCreate
中添加了侦听器,则必须在onDestroy
中将其删除.
- If you have added the listener in
onStart
you have to remove it inonStop
. - If you have added the listener in
onResume
you have to remove it inonPause
. - If you have added the listener in
onCreate
you have to remove it inonDestroy
.
但是请记住,总是调用onDestroy
是 not
,所以最后一个选项并不总是一个好的选择.
But remember onDestroy
is not
always called, so the last option in not always a good choice.
There is another approach in which there is no need to remove the listener and that is when using addListenerForSingleValueEvent:
为该位置的数据中的单个更改添加一个侦听器.
Add a listener for a single change in the data at this location.
这篇关于我是否应该删除ValueEventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!