Ad

When Should I Remove OnCompleteListener?

I've read this answer where it says there is no need to remove any listener when using get() function, does this apply for set(), update() and delete()?

How can I distinguish when the listener is needed to be removed or not? I'm very confused and I'm struggling with this listener stuff for days. Thanks.

Ad

Answer

You only need to remove a listener if you're actually using a true listener - ie, listening to live updates on a record. So if you're just using get or set or update or delete, those are one-time events with addListenerForSingleValueEvent that don't need a true listener despite the name (and don't need any listener removal). You would just likely want a completion handler (eg, addOnSuccessListener) so you can do something after the query is done.

If you're using something like onDataChange, you're polling/listening to the data for changes and you'll want to remove that listener when you switch screens or navigate away from that component.

The naming confuses things a little in Java/Kotlin for this reason - think of a listener and the need to remove it if you're watching or monitoring the data in a polling manner. If you're just doing one-time transactions, no need to remove anything.

Ad
source: stackoverflow.com
Ad