Home > database >  Update Firestore database just before internet disconnect
Update Firestore database just before internet disconnect

Time:12-16

Future<void> setActiveDataToApi(
      String referencePath1, String referencePath2, bool activeState) async {
    await _firestore
        .collection(referencePath1)
        .doc(referencePath2)
        .update({"active": activeState});

I want update user active status just before internet disconnect, how can I do that?

This one is update data my database, I'll update timestamp too but if I periodically update data like 10 second it cost me too much, OnDisconnect()/onDisconnectSetValue() function not exist for firestore and I think it's not for internet just for close app. I use firebase/cloud firestore

CodePudding user response:

u can use the AppLifeCycle to achieve this!

https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver-class.html


class _CustomState
    extends State<WidgetBindingsObserverSample> with WidgetsBindingObserver {
     @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

 @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if(state==AppLifecycleState.paused){
       _syncStatus(status: <Update DB value to offline> );
       return;
    }
    if(state== AppLifecycleState.resumed){
    _syncStatus(status: <Update DB value to online> );
       return;
    }

  }
    }

Note: this is just an example this can be further optimised and improved

If u want to actually update status whether the user is connected to network or not u can use connectivity_plus, the process for this can be diff, u will have to listen for any network changes for the api provided in the package and call ur api depending on which connection status u wanted to update

CodePudding user response:

There is no reliable way to detect when the internet connection is about to disappear. Imagine being in a train that drives into the tunnel. The first time the app can know that there's no connection is when that connection is already gone, and by then it's too late to write to the database.

Firebase Realtime Database's onDisconnect handler, send a write operation to the server when they are connected, that the server then executes when it detects that the client is gone. There is no equivalent in Firestore, because the wire protocol Firebase uses is not suited for it.

Since you indicate not wanting to do a periodic update, the easiest way I can think of to do this is to actually use both databases in your app, and then use Cloud Functions to carry an onDisconnect write operation from the Realtime Database to Firestore. This is in fact exactly the approach that is outlined in the documentation solution on building a presence system on Firestore, so I recommend checking that out.

  • Related