Home > front end >  How can I remove a node from a firebase realtime database when the app exits
How can I remove a node from a firebase realtime database when the app exits

Time:01-18

When my app crashes or the user closes the app I want a particular node to be deleted from the real-time database. So, far I am not able to find any way to handle this issue. Could you please point out any reference material or anything of value that can help me implement this? Here I want the availableDrivers to be removed but for that, I need to find the state of the app, how is it done? I want to do this from the app itself and not from the functions that firebase / google services (cloud functions etc..) The scenarios of the app can be like

  1. minimized

  2. force closed

  3. phone dies

  4. no internet etc..

enter image description here

CodePudding user response:

There's no 100% reliable way of executing code (especially network calls) "when the app exits". What if phone's battery just dies, app crashes or is force closed?

One way to overcome this is remodelling your documents so that instead of removing them, they contain a "last active" timestamp. This timestamp is bumped periodically when the app is active. When timestamp is less than this period from now, document can be considered "inactive" so you query with .where("lastActiveTimestamp", ">=", Date.now() - period) (pseudocode). You can also write a firebase function to cleanup inactive documents to optimise the db.

CodePudding user response:

What you're describing is the purpose of Firebase's onDisconnect method. This this method you can register an operation while you are connected to the database backend, which is then executed once the backend notices that the connection is gone.

A simple example:

// Somewhere in your application, trigger that the user is online:
DatabaseReference ref = FirebaseDatabase.instance.ref("users/123/status");
await ref.set(true);
// And after;
// Create an OnDisconnect instance for your ref and set to false,
// the Firebase backend will then only set the value on your ref to false
// when your client goes offline.
OnDisconnect onDisconnect = ref.onDisconnect();
await onDisconnect.set(false);

The onDisconnect can be triggered either through a clean disconnect, where the client informs the server it is about to disconnect, or through a dirty disconnect, where the client simply stops communicating with the server (for example in the case of a crash, or an actual loss of the physical connection). In the latter case, it may take up to a few minutes before the server detects that the client is gone, and thus runs the onDisconnect handlers for that client.

Also see the FlutterFire documentation on offline capabilities.

  •  Tags:  
  • Related