Home > Blockchain >  How do I use Firebase database Offline Capabilities
How do I use Firebase database Offline Capabilities

Time:04-30

I have a user when logged in creates a node in the firebase database, when the app crashes or the user logs out I want that node to be removed. In the function getCurrentOnlineUserInfo I have embedded the onDisconnect function such that when the app is closed I want the driverOffline to be fired - in which I have Geofire.removeLocation(currentFirebaseUser!.uid); which will remove the node from the firebase. In short I want driverOffline to be called only when the user disconnect. So, far I have the code but not the logic.

  static void getCurrentOnlineUserInfo() async {
    firebaseUser = FirebaseAuth.instance.currentUser!;

    String userId = firebaseUser!.uid;

    late DatabaseReference userRef =
        FirebaseDatabase.instance.ref().child('users').child('users/$userId');
   
    userRef.once().then((DatabaseEvent databaseEvent) {
      if (databaseEvent.snapshot.value != null) {
        userCurrentInfo = Users.fromSnapShot(databaseEvent.snapshot);
        // print('my name is ${userCurrentInfo.name}');
      }
    });

    await userRef.set(true);
    OnDisconnect onDisconnect = driversRef.onDisconnect();
    await onDisconnect.set(false);
    driverOffline(); // driver offline should be called only when the user is disconnected ?
  }

  static void driverOffline() async {
    Geofire.removeLocation(currentFirebaseUser!.uid); //remove this node
    rideRequestRef!.onDisconnect();

    await rideRequestRef!.remove();
    
    LocationManager().stop();
   
  }

CodePudding user response:

Firebase's onDisconnect handlers work by sending an instruction to the database when the client is connected, that the server then executes once it detects that the client has disconnected. There is no way to run from the client anymore in such a situation, as it has already disconnected.

So instead of this:

await userRef.set(true);
OnDisconnect onDisconnect = driversRef.onDisconnect();
await onDisconnect.set(false);

You should do this:

await userRef.set(true);
driversRef.onDisconnect().set(false);

The set(false) now runs on the server, once that detects that the client has disconnected (which may take a few minutes).

Same to remove rideRequestRef once the client has disconnected, you need to run this while the client is connected:

rideRequestRef!.onDisconnect().remove();

This send the instruction to the database server

  • Related