Removing continuous Firebase listeners on Fragment

2019-08-17 14:09发布

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.

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

fuSetListener();  

These functions retrieve and save the data in global variables.

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
}

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.

1条回答
Root(大扎)
2楼-- · 2019-08-17 14:38

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

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.

Hope it helps.

查看更多
登录 后发表回答