我真的应该删除 ValueEventListener 吗? [英] Should I actually remove the ValueEventListener?

查看:24
本文介绍了我真的应该删除 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:

  1. 如果您在 onStart 中添加了侦听器,则必须在 onStop 中将其删除.
  2. 如果您在 onResume 中添加了侦听器,则必须在 onPause 中将其删除.
  3. 如果您在 onCreate 中添加了侦听器,则必须在 onDestroy 中将其删除.
  1. If you have added the listener in onStart you have to remove it in onStop.
  2. If you have added the listener in onResume you have to remove it in onPause.
  3. If you have added the listener in onCreate you have to remove it in onDestroy.

但请记住,onDestroy 总是被not 调用,因此最后一个选项并不总是一个好的选择.

But remember onDestroy is not always called, so the last option in not always a good choice.

还有另一种无需删除侦听器的方法,那就是使用 addListenerForSingleValueEvent:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆