我是否应该删除ValueEventListener? [英] Should I actually remove the ValueEventListener?

查看:66
本文介绍了我是否应该删除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.

还有另一种方法,其中不需要删除侦听器,即使用

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天全站免登陆