在片段更改时删除连续的Firebase侦听器 [英] Removing continuous Firebase listeners on Fragment change

查看:68
本文介绍了在片段更改时删除连续的Firebase侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中的每个Fragment都有自己的连续Firebase侦听器集.活动的Fragment更改后,这些将不再需要,但是,侦听器将继续在后台运行.除此之外,这些旧的侦听器可能会触发先前Fragment的View更新,这可能会使应用程序崩溃.因此,一旦Fragment更改,我想整理一下并清理听众.我不知道如何,但是我有一个替代解决方案,我对您的想法和建议感到好奇.

Each Fragment in my application has their own set of continuous Firebase listeners. These become unnecessary once the active Fragment has changed, however, the listeners continue in the background. Besides that, these old listeners may trigger View updates for the previous Fragment, which may then crash the application. So, I'd like to be tidy and clean up the listeners once the Fragment changes. I do not know how, but I have an alternative solution and I was curious about your thoughts and suggestions.

在片段onCreate中调用侦听器函数,例如:

The listener functions are called in the Fragments onCreate, for example:

fuSetListener();  

这些函数检索数据并将其保存在全局变量中.

These functions retrieve and save the data in global variables.

在Firebase侦听器的onDataChange中,我执行以下if语句来检查是否应删除该侦听器:

In the onDataChange of the Firebase listener I perform this if-statement to check if the listener should be removed:

if(getActivity()==null){ 
    reference.removeEventListener(this); 
} else {
    // Perform necessary onDataChange actions
}

因此出现了问题,如果片段已更改,getActivity()仅返回null吗?还是getActivity()返回null而无需更改Fragment并弄乱我的Fragments目的?

So the question arises, does getActivity() only return null in case the Fragment has changed? Or may getActivity() return null without changing the Fragment and mess up my Fragments purpose?

我已多次使用此方法,但尚未遇到麻烦,但我想在继续之前与您联系.

I have applied this method a couple of times and do not run into trouble yet, but I wanted to check with you before proceeding.

推荐答案

您需要相应地删除片段的life-cycle侦听器.

You need to remove the listener accordingly to the life-cycle of your fragment.

如果已在onStart中添加了侦听器,则必须在onStop中将其删除. 如果已在onResume中添加了侦听器,则必须在onPause中将其删除. 如果已在onCreate中添加了侦听器,则必须在onDestroy中将其删除. 但是请记住,onDestroy并不总是被调用.

If you have added the listener in onStart you have to remove it in onStop. If you have added the listener in onResume you have to remove it in onPause. If you have added the listener in onCreate you have to remove it in onDestroy. But remember onDestroy is not always called.

希望有帮助.

这篇关于在片段更改时删除连续的Firebase侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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