Should Firebase listeners be removed when a Native app is "backgrounded"?

Viewed 102

It's considered good practice to remove listeners from Firebase databases (whether that be Cloud Firestore or Realtime Database) when the listening components are unmounted.

In a lot of applications, mine included (React Native app), this might not happen very often.

For example, when my user is authenticated (signed in), they are subscribed to a number of listeners on both RTDB and CFS. Things like notifications and messages and other "realtime" updates i want them to see app-wide - think notification "badges" for example or "unread messages".

Developers of Native applications will know that apps can remain "backgrounded" for long periods of time. And with auth refreshing, users will rarely log out of my application. This means that those components are never (or rarely) unmounted and thus, remain subscribed to updates - i think.

Should i be adding logic that removes those subscribers to realtime data when a user backgrounds the application, only to re-instate them when they foreground again?

1 Answers

What you're asking is primarily a matter of opinion, which is off-topic for Stack Overflow. That said, you should probably take some time to understand the ramifications of leaving listeners added indefinitely.

A listener that's not removed when the user isn't looking at your app still incurs the cost of downloading updates to the documents it's listening to. Whether or not that's acceptable is entirely up to you.

The host OS will likely throttle the network access of app that can't be seen by the user after some time. This is for the benefit of the user, so poorly implemented apps don't consume excess network and battery. You can't depend on these listeners to work properly when this happens. If you want listeners to stay active while the app isn't visible, you will need to tell the host OS what you want using whatever APIs it provides. Even then, you don't have any guarantees, as the OS may simply kill an invisible app in order to reclaims resources.

You will have to decide for yourself when it makes sense add and remove listeners, after you understand the behavior apps on the given OS.

Related